• 2009-02-03

    java多线程同步设计wait/notify机制 - [Java]

    版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
    http://allantaylor.blogbus.com/logs/34563464.html

    多线程之间需要协调工作。例如,浏览器的一个显示图片的线程displayThread想要执行显示图片的任务,必须等待下载线程downloadThread将该图片下载完毕。如果图片还没有下载完,displayThread可以暂停,当downloadThread完成了任务后,再通知displayThread“图片准备完毕,可以显示了”,这时,displayThread继续执行。

    以上逻辑简单的说就是:如果条件不满足,则等待。当条件满足时,等待该条件的线程将被唤醒。在Java中,这个机制的实现依赖于wait/notify。等待机制与锁机制是密切关联的。例如:

    synchronized(obj) {
        while(!condition) {
            obj.wait();
        }
        obj.doSomething();
    }

    当线程A获得了obj锁后,发现条件condition不满足,无法继续下一处理,于是线程A就wait()。

    在另一线程B中,如果B更改了某些条件,使得线程A的condition条件满足了,就可以唤醒线程A:

    synchronized(obj) {
        condition = true;
        obj.notify();
    }

    需要注意的概念是:

    # 调用obj的wait(), notify()方法前,必须获得obj锁,也就是必须写在synchronized(obj) {...} 代码段内。

    # 调用obj.wait()后,线程A就释放了obj的锁,否则线程B无法获得obj锁,也就无法在synchronized(obj) {...} 代码段内唤醒A。

    # 当obj.wait()方法返回后,线程A需要再次获得obj锁,才能继续执行。

    # 如果A1,A2,A3都在obj.wait(),则B调用obj.notify()只能唤醒A1,A2,A3中的一个(具体哪一个由JVM决定)。

    # obj.notifyAll()则能全部唤醒A1,A2,A3,但是要继续执行obj.wait()的下一条语句,必须获得obj锁,因此,A1,A2,A3只有一个有机会获得锁继续执行,例如A1,其余的需要等待A1释放obj锁之后才能继续执行。

    # 当B调用obj.notify/notifyAll的时候,B正持有obj锁,因此,A1,A2,A3虽被唤醒,但是仍无法获得obj锁。直到B退出synchronized块,释放obj锁后,A1,A2,A3中的一个才有机会获得锁继续执行。

     

    synchronized的4种用法

    1.方法声明时使用,放在范围操作符(public等)之后,返回类型声明(void等)之前.即一次只能有一个线程进入该方法,其他线程要想在此时调用该方法,只能排队等候,当前线程(就是在synchronized方法内部的线程)执行完该方法后,别的线程才能进入.
     
          例如:

          public synchronized void synMethod() {
            //方法体
          }

        2.对某一代码块使用,synchronized后跟括号,括号里是变量,这样,一次只有一个线程进入该代码块.例如:

          public int synMethod(int a1){
            synchronized(a1) {
              //一次只能有一个线程进入
            }
          }

        3.synchronized后面括号里是一对象,此时,线程获得的是对象锁.例如:

    public class MyThread implements Runnable {
      public static void main(String args[]) {
        MyThread mt = new MyThread();
        Thread t1 = new Thread(mt, "t1");
        Thread t2 = new Thread(mt, "t2");
        Thread t3 = new Thread(mt, "t3");
        Thread t4 = new Thread(mt, "t4");
        Thread t5 = new Thread(mt, "t5");
        Thread t6 = new Thread(mt, "t6");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();
      }

      public void run() {
        synchronized (this) {
          System.out.println(Thread.currentThread().getName());
        }
      }
    }


     
        对于3,如果线程进入,则得到对象锁,那么别的线程在该类所有对象上的任何操作都不能进行.在对象级使用锁通常是一种比较粗糙的方法。为什么要将整个对象都上锁,而不允许其他线程短暂地使用对象中其他同步方法来访问共享资源?如果一个对象拥有多个资源,就不需要只为了让一个线程使用其中一部分资源,就将所有线程都锁在外面。由于每个对象都有锁,可以如下所示使用虚拟对象来上锁:

    class FineGrainLock {

       MyMemberClass x, y;
       Object xlock = new Object(), ylock = new Object();

       public void foo() {
          synchronized(xlock) {
             //access x here
          }

          //do something here - but don't use shared resources

          synchronized(ylock) {
             //access y here
          }
       }

       public void bar() {
          synchronized(this) {
             //access both x and y here
          }
          //do something here - but don't use shared resources
       }
    }

     

        4.synchronized后面括号里是类.例如:

    class ArrayWithLockOrder{
      private static long num_locks = 0;
      private long lock_order;
      private int[] arr;

      public ArrayWithLockOrder(int[] a)
      {
        arr = a;
        synchronized(ArrayWithLockOrder.class) {//-----------------------------------------这里
          num_locks++;             // 锁数加 1。
          lock_order = num_locks;  // 为此对象实例设置唯一的 lock_order。
        }
      }
      public long lockOrder()
      {
        return lock_order;
      }
      public int[] array()
      {
        return arr;
      }
    }

    class SomeClass implements Runnable
    {
      public int sumArrays(ArrayWithLockOrder a1,
                           ArrayWithLockOrder a2)
      {
        int value = 0;
        ArrayWithLockOrder first = a1;       // 保留数组引用的一个
        ArrayWithLockOrder last = a2;        // 本地副本。
        int size = a1.array().length;
        if (size == a2.array().length)
        {
          if (a1.lockOrder() > a2.lockOrder())  // 确定并设置对象的锁定
          {                                     // 顺序。
            first = a2;
            last = a1;
          }
          synchronized(first) {              // 按正确的顺序锁定对象。
            synchronized(last) {
              int[] arr1 = a1.array();
              int[] arr2 = a2.array();
              for (int i=0; i            value += arr1[i] + arr2[i];
            }
          }
        }
        return value;
      }
      public void run() {
        //...
      }
    }

     

        对于4,如果线程进入,则线程在该类中所有操作不能进行,包括静态变量和静态方法,实际上,对于含有静态方法和静态变量的代码块的同步,我们通常用4来加锁.

    以上4种之间的关系:

        锁是和对象相关联的,每个对象有一把锁,为了执行synchronized语句,线程必须能够获得synchronized语句中表达式指定的对象的锁,一个对象只有一把锁,被一个线程获得之后它就不再拥有这把锁,线程在执行完synchronized语句后,将获得锁交还给对象。
        在方法前面加上synchronized修饰符即可以将一个方法声明为同步化方法。同步化方法在执行之前获得一个锁。如果这是一个类方法,那么获得的锁是和声明方法的类相关的Class类对象的锁。如果这是一个实例方法,那么此锁是this对象的锁。


     

     

      下面谈一谈一些常用的方法:

      wait(),wait(long),notify(),notifyAll()等方法是当前类的实例方法,
       
            wait()是使持有对象锁的线程释放锁;
            wait(long)是使持有对象锁的线程释放锁时间为long(毫秒)后,再次获得锁,wait()和wait(0)等价;
            notify()是唤醒一个正在等待该对象锁的线程,如果等待的线程不止一个,那么被唤醒的线程由jvm确定;
            notifyAll是唤醒所有正在等待该对象锁的线程.
            在这里我也重申一下,我们应该优先使用notifyAll()方法,因为唤醒所有线程比唤醒一个线程更容易让jvm找到最适合被唤醒的线程.

        对于上述方法,只有在当前线程中才能使用,否则报运行时错误java.lang.IllegalMonitorStateException: current thread not owner.


     

     

        下面,我谈一下synchronized和wait()、notify()等的关系:

    1.有synchronized的地方不一定有wait,notify

    2.有wait,notify的地方必有synchronized.这是因为wait和notify不是属于线程类,而是每一个对象都具有的方法,而且,这两个方法都和对象锁有关,有锁的地方,必有synchronized。

    另外,请注意一点:如果要把notify和wait方法放在一起用的话,必须先调用notify后调用wait,因为如果调用完wait,该线程就已经不是current thread了。如下例:

    /**
     * Title:        Jdeveloper's Java Projdect
     * Description:  n/a
     * Copyright:    Copyright (c) 2001
     * Company:      soho 
    http://www.ChinaJavaWorld.com
     * @author jdeveloper@21cn.com
     * @version 1.0
     */
    import java.lang.Runnable;
    import java.lang.Thread;

    public class DemoThread
        implements Runnable {

      public DemoThread() {
        TestThread testthread1 = new TestThread(this, "1");
        TestThread testthread2 = new TestThread(this, "2");

        testthread2.start();
        testthread1.start();

      }

      public static void main(String[] args) {
        DemoThread demoThread1 = new DemoThread();

      }

      public void run() {

        TestThread t = (TestThread) Thread.currentThread();
        try {
          if (!t.getName().equalsIgnoreCase("1")) {
            synchronized (this) {
              wait();
            }
          }
          while (true) {

            System.out.println("@time in thread" + t.getName() + "=" +
                               t.increaseTime());

            if (t.getTime() % 10 == 0) {
              synchronized (this) {
                System.out.println("****************************************");
                notify();
                if (t.getTime() == 100)
                  break;
                wait();
              }
            }
          }
        }
        catch (Exception e) {
          e.printStackTrace();
        }
      }

    }

    class TestThread
        extends Thread {
      private int time = 0;
      public TestThread(Runnable r, String name) {
        super(r, name);
      }

      public int getTime() {
        return time;
      }

      public int increaseTime() {
        return++time;
      }

    }

        下面我们用生产者/消费者这个例子来说明他们之间的关系:

        public class test {
      public static void main(String args[]) {
        Semaphore s = new Semaphore(1);
        Thread t1 = new Thread(s, "producer1");
        Thread t2 = new Thread(s, "producer2");
        Thread t3 = new Thread(s, "producer3");
        Thread t4 = new Thread(s, "consumer1");
        Thread t5 = new Thread(s, "consumer2");
        Thread t6 = new Thread(s, "consumer3");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();
      }
    }

    class Semaphore
        implements Runnable {
      private int count;
      public Semaphore(int n) {
        this.count = n;
      }

      public synchronized void acquire() {
        while (count == 0) {
          try {
            wait();
          }
          catch (InterruptedException e) {
            //keep trying
          }
        }
        count--;
      }

      public synchronized void release() {
        while (count == 10) {
          try {
            wait();
          }
          catch (InterruptedException e) {
            //keep trying
          }
        }
        count++;
        notifyAll(); //alert a thread that's blocking on this semaphore
      }

      public void run() {
        while (true) {
          if (Thread.currentThread().getName().substring(0,8).equalsIgnoreCase("consumer")) {
            acquire();
          }
          else if (Thread.currentThread().getName().substring(0,8).equalsIgnoreCase("producer")) {
            release();
          }
          System.out.println(Thread.currentThread().getName() + " " + count);
        }
      }
    }

           生产者生产,消费者消费,一般没有冲突,但当库存为0时,消费者要消费是不行的,但当库存为上限(这里是10)时,生产者也不能生产.请好好研读上面的程序,你一定会比以前进步很多.

          上面的代码说明了synchronized和wait,notify没有绝对的关系,在synchronized声明的方法、代码块中,你完全可以不用wait,notify等方法,但是,如果当线程对某一资源存在某种争用的情况下,你必须适时得将线程放入等待或者唤醒.


    收藏到:Del.icio.us