线程间通讯学习【六】

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值