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;
}
@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
2518

被折叠的 条评论
为什么被折叠?



