标签:
JDK1.5中提供了多线程升级解决方案。该示例中实现了本方只唤醒对方的操作。
import java.util.concurrent.locks.*; class Resource { private String name; private int num=0; boolean flag; private Lock lock=new ReentrantLock(); private Condition condition_set=lock.newCondition(); private Condition condition_get=lock.newCondition(); public void set(String name) throws InterruptedException { lock.lock(); try { while(flag) condition_set.await(); this.name=name+"_"+num++; System.out.println(Thread.currentThread().getName()+"生产者"+this.name); flag=true; condition_get.signal(); } finally { lock.unlock(); } } public void get() throws InterruptedException { lock.lock(); try { while(!flag) condition_get.await(); System.out.println(Thread.currentThread().getName()+"消费者.............."+this.name); flag=false; condition_set.signal(); } finally { lock.unlock(); } } } class Producer implements Runnable { private Resource r; Producer(Resource r) { this.r=r; } public void run() { while (true) { try { r.set("商品"); } catch (InterruptedException e) { } } } } class Consumer implements Runnable { private Resource r; Consumer(Resource r) { this.r=r; } public void run() { while (true) { try { r.get(); } catch (InterruptedException e) { } } } } class ProducerConsumerDemo1 { public static void main(String[] args) { Resource r=new Resource(); Producer p=new Producer(r); Consumer c=new Consumer(r); Thread t1=new Thread(p); Thread t2=new Thread(p); Thread t3=new Thread(c); Thread t4=new Thread(c); t1.start(); t2.start(); t3.start(); t4.start(); System.out.println("Hello World!"); } }
标签:
原文地址:http://blog.csdn.net/iemdm1110/article/details/51357107