- 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呢?求大神帮忙 |