黑马程序员技术交流社区
标题:
生产者消费者问题
[打印本页]
作者:
yefeidd
时间:
2015-8-12 17:27
标题:
生产者消费者问题
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/*
* @jdk5.0以后的版本中,用lock()等方法替换了synchronized,用condition替换了wait,notify,notifyAll。
* @同样的生产者消费者问题。
*/
class Resource2// 资源
{
private String name;
private int Count = 1;
private Boolean flag = false;
private Lock lock = new ReentrantLock();
private Condition condition_con = lock.newCondition();//消费者对象
private Condition condition_pro = lock.newCondition();//生产者对象
public void set(String name) throws InterruptedException// await未抛出异常(生产者)
{
lock.lock();
// if(flag)//将if替换为while可以避免多个线程生产消费的安全问题
try {
while (flag)
condition_pro.await();// await要抛出异常,因为没有写catch所有throw一下
this.name = name + "-------" + Count++;
System.out.println(Thread.currentThread().getName() + "---生产者"
+ this.name);
condition_con.signal();//消费者唤醒
flag = true;
} finally {
lock.unlock();
}
}
public void out() throws InterruptedException //消费者
{
lock.lock();
try {
// if(!flag)//将if替换为while可以避免多个线程生产消费的安全问题
while (!flag)
condition_con.await();
System.out.println(Thread.currentThread().getName()
+ "----------消费者" + this.name);
flag = false;
condition_pro.signal();//生产者唤醒
} finally {
lock.unlock();
}
}
}
class producer2 implements Runnable {
private Resource2 r;
producer2(Resource2 r) {
this.r = r;
}
public void run() {
while (true) {
try {
r.set("商品");
} catch (InterruptedException e) {
}
}
}
}
class Consumer2 implements Runnable {
private Resource2 r;
Consumer2(Resource2 r) {
this.r = r;
}
public void run() {
while (true) {
try {
r.out();
} catch (InterruptedException e) {
}
}
}
}
public class ProducerConsumerDemo2 {
public static void main(String[] args) {
Resource2 r = new Resource2();
producer2 pro = new producer2(r);
Consumer2 con = new Consumer2(r);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
复制代码
作者:
沉醉
时间:
2015-8-12 17:41
yefeidd 发表于 2015-8-12 17:27
不错,膜拜!!
作者:
星语千寻
时间:
2015-8-12 19:10
路过。。。
作者:
yefeidd
时间:
2015-8-13 10:37
沉醉 发表于 2015-8-12 17:41
不错,膜拜!!
饿,,,笔记而已
作者:
yefeidd
时间:
2015-8-13 10:38
星语千寻 发表于 2015-8-12 19:10
路过。。。
送你个酱油瓶
作者:
耀阳圣尊
时间:
2015-8-13 11:36
写的不错,赞一个
作者:
风华正茂
时间:
2015-8-13 12:59
楼主得笔记写得不错,赞一个
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2