一个synchronized,wait,notifyall的例子

package test;
public class ThreadTest {

 public static void main(String[] args) {
  Thread t1 = new Thread(new  Runnable1());
  Thread t2 = new Thread(new  Runnable2());
  
  t1.start();
  t2.start() ;
  
  try {
   t1.join() ;
  } catch (InterruptedException e) {
   throw new RuntimeException(e.getMessage());
  }
  try {
   t2.join() ;
  } catch (InterruptedException e) {
   throw new RuntimeException(e.getMessage());
  }
  
  System.out.println("at last:"+counter);
 }
 
 public static int counter = 0 ;
}

 

 

 

package test;

public class Runnable1 implements Runnable {
 @Override
 public void run() {
  
  for (int i= 0 ; i < 1000000 ; i ++)
  {
   synchronized (ThreadTest.class) {
    if (ThreadTest.counter > 0)
     try {
      ThreadTest.class.wait();
     } catch (InterruptedException e) {
      throw new RuntimeException(e.getMessage());
     }
    ThreadTest.counter ++ ;
    System.out.println(ThreadTest.counter);
    ThreadTest.class.notifyAll();
   }
  }
 }
}

 

 

package test;

public class Runnable2 implements Runnable {

 @Override
 public void run() {
  for (int i= 0 ; i < 1000000 ; i ++)
  {
   synchronized (ThreadTest.class) {
    if (ThreadTest.counter < 0)
     try {
      ThreadTest.class.wait();
     } catch (InterruptedException e) {
      throw new RuntimeException(e.getMessage());
     }
    ThreadTest.counter -- ;
    ThreadTest.class.notifyAll();
   }
  }
 }

}

 

wait和notifyall的使用需要在synchronized段内且与synchronized锁定的对象为同一对象,因为wait调用需要释放一个锁,如果锁不存在就抛异常。

 

posted on 2010-07-13 21:37  sunliho  阅读(747)  评论(0编辑  收藏  举报