标签:over stack java current span ace ati 方法 rri
package proxy; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; class Product{ public int num; } class Produce implements Runnable{ public Product pro; //public Object obj=new Object(); public Produce(Product pro){ this.pro=pro; } @Override public void run() { while(true) { synchronized(pro){ while(pro.num==1) { try { pro.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("生产了一个"); pro.num++; pro.notifyAll(); } } } } class Consumer implements Runnable{ public Product pro; //public Object obj=new Object(); public Consumer(Product pro){ this.pro=pro; } @Override public void run() { while(true) { synchronized(pro){ while(pro.num==0) { try { pro.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("消费了一个"); pro.num--; pro.notifyAll(); } } } } public class Main { public static void main(String[] args) { ExecutorService pool=Executors.newFixedThreadPool(2); Product pr=new Product(); pr.num=0; Produce pro=new Produce(pr); Consumer con=new Consumer(pr); pool.execute(pro); pool.execute(con); } }
使用wait,notify时,一定要先获取该对象的锁,才可以调用。即:外面要使用synchronized包含。注意只有相同的对象,调用notify方法,才可以唤醒调用wait进入唤醒的方法。
标签:over stack java current span ace ati 方法 rri
原文地址:http://www.cnblogs.com/chenjiewhu/p/7502705.html