147_多线程(线程间通信-生产者消费者JDK5.0升级版)
2015-10-21 23:33
609 查看
/*JDK1.5及以上提供了多线程升级解决方案。
将同步Synchronized替换成Lock操作。
将Object中的wait,notify,notifyAll,用Condition对象替换。
该对象可以用lock进行获取。
该实例中实现了本方只唤醒对方的操作。
及生产者只唤醒消费者。
消费者只唤醒生产者。
*/
import java.util.concurrent.locks.*;
class ProducerConsumer{
public static void main(String[] args){
Resource r = new Resource();
Producer pro = new Producer(r);
Consumer con = new Consumer(r);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Resource{
private String name;
private int count = 1;
private boolean flag = false;
private Lock lock = new ReentrantLock();
private Condition conProducer = lock.newCondition();
private Condition conConsumer = lock.newCondition();
public void set(String name)throws InterruptedException{
lock.lock();
try{
while(flag)
conProducer.await();
this.name = name +"--"+count++;
System.out.println(Thread.currentThread().getName()+
"-生产者-"+this.name);
flag = true;
conConsumer.signal();
}
finally{
lock.unlock();
}
}
public void out()throws InterruptedException{
lock.lock();
try{
while(!flag)
conConsumer.await();
System.out.println(Thread.currentThread().getName()+
"-消费者-"+this.name);
flag = false;
conProducer.signal();
}
finally{
lock.unlock();
}
}
}
class Producer implements Runnable{
private Resource res;
Producer(Resource res){
this.res = res;
}
public void run(){
while(true){
try{
res.set("+商品+");
}
catch(InterruptedException e){
}
}
}
}
class Consumer implements Runnable{
private Resource res;
Consumer(Resource res){
this.res = res;
}
public void run(){
while(true){
try{
res.out();
}
catch(InterruptedException e){
}
}
}
}
相关文章推荐
- Java基础学习__多线程(线程间通信--生产者消费者JDK5.0升级版)
- JAVA 线程间通信 -生产者消费者JDK5.0升级版
- JAVA 线程间通信 -生产者消费者JDK5.0升级版
- JAVA 线程间通信 -生产者消费者JDK5.0升级版
- Java 多线程(三)线程间的通信jdk1.5中Lock,Condition---生产者消费者为例
- 多线程执行多任务(线程通信):生产者消费者模型(一)
- Java基础学习6_多线程(线程间通信--生产者消费者)
- java多线程线程通信——生产者和消费者
- 【多线程】生产者和消费者线程间通信
- 【java多线程】【生产者与消费者】【JDK5.0升级版】
- 多线程—03—线程间通信、生产者消费者
- (九)Java入门--多线程(5)线程通信--多生产者多消费者
- 多线程(线程间通信-多生产者多消费者问题-JDK1.5新特性-Lock
- java多线程-线程间通信_生产者消费者
- Java多线程之线程间通信--生产者/消费者模式
- java多线程:线程间的通信-生产者和消费者(三)
- 黑马程序员自学笔记————多线程 线程间通信之生产者消费者问题;
- 多线程执行多任务(线程通信):生产者消费者模型(二)
- python多线程(3)---生产者与消费者(线程通信)和Queue模块
- 黑马程序员--JAVA基础复习之多线程(三)线程间通信 生产者消费者