线程间通讯学习【六】sohu - 超凡娱乐

线程间通讯学习【六】sohu

2019-02-08 07:56:28 | 作者: 语梦 | 标签: 苹果,出产,顾客 | 浏览: 8830

import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; * 线程间通讯-出产者、顾客 jdk5.0晋级版 * jdk1.5 中供给了多线程晋级解决方案。 * 将同步的 synchronized 替换成显现的 Lock操作。 * 讲Object中的 wait notify notifyAll 替换成Condition目标 * 该Condition目标能够经过Lock锁的 newCondition()办法进行获取 * @author zzl class MyResource { private String name; private int number = 1; private boolean flag = false; private Lock lock = new ReentrantLock(); private Condition condition_producer = lock.newCondition(); private Condition condition_consumer = lock.newCondition(); //资源的出产 public void set(String name) { //拿到锁 lock.lock(); try { while (flag) { try { //出产的Condition await; condition_producer.await(); } catch (InterruptedException e) { e.printStackTrace(); this.name = name + "......" + number++; System.out.println(Thread.currentThread().getName() + "...出产者..." + this.name); this.flag = true; //消费的Condition唤醒 condition_consumer.signal(); } finally { //开释锁 lock.unlock(); //资源的消费 public void print() { //拿到锁 lock.lock(); try { while (!flag) { try { //消费的Condition await; condition_consumer.await(); } catch (InterruptedException e) { e.printStackTrace(); System.out.println(Thread.currentThread().getName() + "-顾客-" + this.name); this.flag = false; //出产的Condition唤醒 condition_producer.signal(); } finally { //开释锁 lock.unlock(); class Producer implements Runnable { private MyResource r; public Producer(MyResource r) { this.r = r; @Override public void run() { while (true) { r.set("苹果"); class Consumer implements Runnable { private MyResource r; public Consumer(MyResource r) { this.r = r; @Override public void run() { while (true) { r.print(); public class ProducerConsumerDemo { public static void main(String[] args) { MyResource r = new MyResource(); 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();
运转作用:
Thread-0...出产者...苹果......37809
Thread-2-顾客-苹果......37809
Thread-1...出产者...苹果......37810
Thread-3-顾客-苹果......37810
Thread-0...出产者...苹果......37811
Thread-2-顾客-苹果......37811
Thread-1...出产者...苹果......37812
Thread-3-顾客-苹果......37812
Thread-0...出产者...苹果......37813
Thread-2-顾客-苹果......37813
Thread-1...出产者...苹果......37814
Thread-3-顾客-苹果......37814
Thread-0...出产者...苹果......37815
Thread-2-顾客-苹果......37815
版权声明
本文来源于网络,版权归原作者所有,其内容与观点不代表超凡娱乐立场。转载文章仅为传播更有价值的信息,如采编人员采编有误或者版权原因,请与我们联系,我们核实后立即修改或删除。

猜您喜欢的文章