黑马程序员技术交流社区
标题:
多线程问题
[打印本页]
作者:
雨下阳光
时间:
2014-9-27 22:21
标题:
多线程问题
import java.util.concurrent.locks.*;
/*
* 生产者生产烤鸭,消费者消费
* 两个或多个生产者,生产一次就等待消费一次
* 多个消费者,等待生产者生产一次就消费
* 生产到100个就停止生产
*/
class Store {
private boolean flag=true;
private String name;
private int count=1;
Lock lock=new ReentrantLock();//创建一个锁对象
Condition con=lock.newCondition();//获得监视器对象
public void set(String name) {
lock.lock();
try{
while(flag)
try{con.await(); } catch(Exception e) {}
this.name=name+count;
count++;
System.out.println(Thread.currentThread().getName()+":"+"生产者生产"+this.name);
flag=false;
con.signalAll();
}
finally {lock.unlock();}
}
public void out() {
lock.lock();
try{
while(!flag)
try{con.await();}catch(Exception e) {}
System.out.println(Thread.currentThread().getName()+":"+"消费者消费"+this.name);
flag=true;
con.signalAll();
}
finally {lock.unlock();}
}
}
class Producer implements Runnable {
Store r;
Producer(Store r) {
this.r=r;
}
public void run() {
while(true) {
r.set("烤鸭");
}
}
}
class Consumer implements Runnable {
Store r;
Consumer(Store r) {
this.r=r;
}
public void run() {
while(true) {
r.out();
}
}
}
public class ProducerConsumerDemo {
public static void main(String[] args) {
Store r=new Store();
Producer pro=new Producer(r);
Consumer con=new Consumer(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();
}
}
复制代码
我这个程序与毕老师基本一模一样,为什么结果this.name是null呢?求大神帮忙
作者:
谢建平
时间:
2014-9-28 12:59
while(flag) 还有后面的 flag=true; 生产和消费两对这判断你仔细想下 不对的 不直接给答案了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2