Java 多线程 生产者消费者 jdk1.5后新方法

来源:互联网 发布:完全开源的cms系统 编辑:程序博客网 时间:2024/05/19 02:01
/*生产者,消费者多生产者,多消费者的问题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();}}

原创粉丝点击