线程间通讯学习【六】
package com.zzl.thread;import java.util.concurrent.locks.Condition;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;}@Overridepublic void run() {while (true) {r.set("苹果");}}}class Consumer implements Runnable {private MyResource r;public Consumer(MyResource r) {this.r = r;}@Overridepublic 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...生产者...苹果......37809Thread-2---------消费者---------苹果......37809Thread-1...生产者...苹果......37810Thread-3---------消费者---------苹果......37810Thread-0...生产者...苹果......37811Thread-2---------消费者---------苹果......37811Thread-1...生产者...苹果......37812Thread-3---------消费者---------苹果......37812Thread-0...生产者...苹果......37813Thread-2---------消费者---------苹果......37813Thread-1...生产者...苹果......37814Thread-3---------消费者---------苹果......37814Thread-0...生产者...苹果......37815Thread-2---------消费者---------苹果......37815