/*
生产者,消费者
多生产者,多消费者的问题
if判断标记 只有一次 会导致不该运行的线程运行了,出现了数据错误的情况
while判断标记 解决了线程获取执行权后,是否要允许!
notifyAll解决了 本方线程一定会唤醒对方线程(但是影响效率)
notify 只能唤醒一个线程,如果本方唤醒了本方没有意义 而且while判断标记+ notify会导致死锁
Lock接口:出现替代了同步代码块或同步函数,将同步的隐式锁操作变成了显示锁操作
同时更为灵活,可以一个锁上加多组监视器
lock():获取锁
unlock():释放锁,通常需要定义finally 代码块中
Condition接口:出现了替代Object中的wait notify notifyAll方法
将这些监视器方法单独进行了封装,变成Condition监视器对象
可以将任意锁进行组合
wait();
signal();
signalAll();
*/
import java.util.concurrent.locks.*;
class Producer implements Runnable{
private Resource r;
Producer(Resource r){
this.r=r;
}
public void run(){
while(true){
r.set("烤鸭");
}
}
}
class Consumer implements Runnable{
private Resource r;
Consumer(Resource r){
this.r=r;
}
public void run(){
while(true){
r.out();
}
}
}
class Resource{
private String name;
private int count=1;
private boolean flag=false;
//创建一个锁对象
Lock lock=new ReentrantLock();
//通过已有的锁获取该锁上的监视器对象
//Condition con =lock.newCondition();
//通过已有的锁获取两组监视器,一组监视生产者一组监视消费者
Condition producer_con=lock.newCondition();
Condition consumer_con=lock.newCondition();
public void set(String name){
lock.lock();
try{
while(flag){
/*try{this.wait();} catch(InterruptedException e){}*/
try{producer_con.await();} catch(InterruptedException e){}
}
this.name=name+count;
count++;
System.out.println(Thread.currentThread().getName()+"..生产者.."+this.name);
flag=true;
//notify();
//con.signalAll();
consumer_con.signal();
}
finally{
lock.unlock();
}
}
public void out(){
lock.lock();
try{
while(!flag){
/*try{wait();} catch(InterruptedException e){}*/
try{consumer_con.await();} catch(InterruptedException e){}
}
System.out.println(Thread.currentThread().getName()+"..--消费者----.."+this.name);
flag=false;
//notify();
//con.signalAll();
producer_con.signal();
}
finally{
lock.unlock();
}
}
}
class ProducerConsumerDemo2{
public static void main(String[] args) {
Resource r=new Resource();
Producer pro=new Producer(r);
Consumer conn=new Consumer(r);
Thread t0=new Thread(pro);
Thread t1=new Thread(pro);
Thread t2=new Thread(conn);
Thread t3=new Thread(conn);
t0.start();
t1.start();
t2.start();
t3.start();
}
}
Java 多线程 生产者消费者 jdk1.5后新方法
最新推荐文章于 2018-10-16 22:34:31 发布
