ThreadInteraction - juedaiyuer/researchNote GitHub Wiki

#Java多线程-线程的交互#

##线程交互的基础知识##

void notify():唤醒在此对象监视器上等待的单个线程。
void notifyAll():唤醒在此对象监视器上等待的所有线程。
void wait():导致当前的线程等待,直到其他线程调用此对象的 notify()方法或 notifyAll()方法。


package thread;

public class ThreadSum extends Thread {
	int total = 0;

	@Override
	public void run() {

	    synchronized (this) {
	        for (int i = 0; i < 101; i++) {
	            total += i;
	        }
	        //(完成计算了)唤醒在此对象监视器上等待的单个线程,在本例中线程ThreadInteractionTest被唤醒
	        notify();
			System.out.println("TODO");
	    }

	}
}


package thread;

public class ThreadInteractionTest {

	public static void main(String[] args) {
	    ThreadSum sum = new ThreadSum();
	    // 启动计算线程
	    sum.start();
	    // 线程ThreadInteractionTest拥有sum对象上的锁。
	    // 线程为了调用wait()或notify()方法,该线程ThreadInteractionTest必须是那个对象锁的拥有者
	    synchronized (sum) {
	        try {
	            System.out.println("等待对象sum完成计算。。。");
	            // 当前线程ThreadInteractionTest等待
	            sum.wait();
	        } catch (InterruptedException e) {
	            e.printStackTrace();
	        }
	        System.out.println("sum对象计算的总和是:" + sum.total);
	    }

	}

}

当在对象上调用wait()方法时,执行该代码的线程立即放弃它在对象上的锁。然而调用notify()时,并不意味着这时线程会放弃其锁。如果线程仍然在完成同步代码,则线程在移出之前不会放弃锁。因此,只要调用notify()并不意味着这时该锁变得可用

##多个线程在等待一个对象锁时使用notifyAll()##

package thread;

public class ThreadSum2 extends Thread {
	int total = 0;

	@Override
	public void run() {

	    synchronized (this) {
	        for (int i = 0; i < 101; i++) {
	            total += i;
	        }
	        //通知所有在此对象上等待的线程 
	        notifyAll();
	    }

	}
}

package thread;

public class ThreadInteractionTest2 extends Thread{

	   ThreadSum2 sum;
		
		public ThreadInteractionTest2(ThreadSum2 sum){
		    this.sum=sum;
		}
		
		@Override
		public void run() {
		    synchronized (sum) {
		        try {
		            System.out.println("等待对象sum完成计算。。。");
		            // 当前线程ThreadInteractionTest等待
		            sum.wait();
		        } catch (InterruptedException e) {
		            e.printStackTrace();
		        }
		        System.out.println("sum对象计算的总和是:" + sum.total);
		    }
		}
		
		public static void main(String[] args) {
		    ThreadSum2 sum = new ThreadSum2();
		    
		    //启动三个线程,分别获取计算结果 
		    new ThreadInteractionTest2(sum).start();
		    new ThreadInteractionTest2(sum).start();
		    new ThreadInteractionTest2(sum).start();
		    
		    // 启动计算线程
		    sum.start();
		    
		    
		}

}