日期:2014-05-20 浏览次数:20847 次
public class WaitTest {
	
public final static Object o = "abc";
  
 public static void main(String[] args) {
    	test3();
  }
 public static void test3(){
    	ThreadB b = new ThreadB();
    	
    	b.start();
    	
        synchronized (o) {
            try {
                System.out.println("Waiting for b to complete...");
                o.wait();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Total is: " + b.total);       	
        }      
    }
}
class ThreadB extends Thread {
    int total = 0;
     
    public void run() {
        synchronized (WaitTest.o) {
            System.out.println("ThreadB");
            for (int i = 0; i < 50; i++) {
                total += i;
                try {
                    Thread.sleep(100);
                    System.out.print(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }                          	
            }
            System.out.println();
            WaitTest.o.notify();
        }
    }  
}
 public static void test3(){
    	ThreadB b = new ThreadB();
    	
        synchronized (o) {
            try {
                System.out.println("Waiting for b to complete...");
                o.wait();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Total is: " + b.total);       	
        }  
        
        b.start();
    }
public static void test3(){
ThreadB b = new ThreadB();
b.start();
synchronized (o) {//主线程获取o上的锁
try {
System.out.println("Waiting for b to complete...");