A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

  1. /*
  2. 对于多个生产者和消费者
  3. 为什么要定义while判断标识
  4. 因为:被唤醒的线程再一次判断标识

  5. 【为什么要定义notfiyAll
  6. 因为需要唤醒对方的线程
  7. 因为只用notfiy,容易出现只唤醒本方线程的情况,导致程序中的所有线程都等待
  8. */
  9. class Rerource
  10. {
  11.         private String name;
  12.         private int count=1;
  13.         private boolean flag=false;
  14.        
  15.         public synchronized void set(String name)
  16.         {
  17.                 while(this.flag)
  18.                         try{this.wait();}catch(Exception e){}
  19.                 this.name=name+"---"+count++;
  20.                 System.out.println(Thread.currentThread().getName()+".....生产者...."+this.name);
  21.                 this.flag=true;
  22.                 this.notifyAll();
  23.         }
  24.         public synchronized void get()
  25.         {
  26.                 while(!this.flag)
  27.                         try{this.wait();}catch(Exception e){}
  28.                 System.out.println(Thread.currentThread().getName()+".....消费者..........."+this.name);
  29.                 this.flag=false;
  30.                 this.notifyAll();
  31.         }
  32. }
  33. class Product implements Runnable
  34. {
  35.         Rerource re=new Rerource();
  36.         Product(Rerource re)
  37.         {
  38.                 this.re=re;
  39.         }
  40.         public void run()
  41.         {
  42.                 while(true)
  43.                 {
  44.                         re.set("+商品+");
  45.                 }
  46.         }
  47. }
  48. class Consumer implements Runnable
  49. {
  50.         Rerource re=new Rerource();
  51.         Consumer(Rerource re)
  52.         {
  53.                 this.re=re;
  54.         }
  55.         public void run()
  56.         {
  57.                 while(true)
  58.                 {
  59.                         re.get();
  60.                 }
  61.         }
  62. }
  63. public class ProductConsumerDome {

  64.         /**
  65.          * @param args
  66.          */
  67.         public static void main(String[] args) {
  68.                 // TODO Auto-generated method stub
  69.                 Rerource r=new Rerource();
  70.                 Product p=new Product(r);
  71.                 Consumer c=new Consumer(r);
  72.                 Thread t1=new Thread(p);
  73.                 Thread t2=new Thread(p);
  74.                 Thread t3=new Thread(c);
  75.                 Thread t4=new Thread(c);
  76.                 t1.start();
  77.                 t2.start();
  78.                 t3.start();
  79.                 t4.start();
  80.         }

  81. }
复制代码
新手上路,多多指教

2 个回复

倒序浏览
顶顶~~。。。。
回复 使用道具 举报
开发中常用实现Runnable接口
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马