黑马程序员技术交流社区

标题: 多线程问题 [打印本页]

作者: 雨下阳光    时间: 2014-9-27 22:21
标题: 多线程问题
  1. import java.util.concurrent.locks.*;

  2. /*
  3. * 生产者生产烤鸭,消费者消费
  4. * 两个或多个生产者,生产一次就等待消费一次
  5. * 多个消费者,等待生产者生产一次就消费
  6. * 生产到100个就停止生产
  7. */
  8. class Store {
  9.         private boolean flag=true;
  10.         private String name;
  11.         private int count=1;
  12.         Lock lock=new ReentrantLock();//创建一个锁对象
  13.         Condition con=lock.newCondition();//获得监视器对象
  14.         public  void set(String name) {
  15.                 lock.lock();
  16.                 try{               
  17.                         while(flag)
  18.                             try{con.await(); } catch(Exception e) {}
  19.                    this.name=name+count;
  20.                    count++;
  21.                         System.out.println(Thread.currentThread().getName()+":"+"生产者生产"+this.name);
  22.                 flag=false;
  23.                 con.signalAll();       
  24.                 }
  25.                 finally {lock.unlock();}
  26.         }
  27.         public  void out() {
  28.                 lock.lock();
  29.                 try{
  30.                     while(!flag)                        
  31.                         try{con.await();}catch(Exception e) {}               
  32.                         System.out.println(Thread.currentThread().getName()+":"+"消费者消费"+this.name);
  33.                 flag=true;
  34.                 con.signalAll();
  35.                 }
  36.                 finally {lock.unlock();}
  37.     }
  38. }
  39. class Producer implements Runnable {
  40.         Store r;
  41.         Producer(Store r) {
  42.                 this.r=r;
  43.         }
  44.         public void run() {
  45.                 while(true) {
  46.                 r.set("烤鸭");       
  47.                 }
  48.         }
  49. }
  50. class Consumer implements Runnable {
  51.         Store r;
  52. Consumer(Store r) {
  53.         this.r=r;
  54. }
  55. public void run() {
  56.         while(true) {
  57.         r.out();       
  58.         }       
  59.   }
  60. }  
  61. public class ProducerConsumerDemo {

  62.         public static void main(String[] args) {
  63.                 Store r=new Store();
  64.       Producer pro=new Producer(r);
  65.       Consumer con=new Consumer(r);
  66. Thread t1=new Thread(pro);
  67. Thread t2=new Thread(pro);
  68. Thread t3=new Thread(con);
  69. Thread t4=new Thread(con);
  70. t1.start();
  71. t2.start();
  72. t3.start();
  73. t4.start();
  74.         }
  75. }
复制代码

我这个程序与毕老师基本一模一样,为什么结果this.name是null呢?求大神帮忙
作者: 谢建平    时间: 2014-9-28 12:59
while(flag)     还有后面的 flag=true;    生产和消费两对这判断你仔细想下  不对的  不直接给答案了




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2