首页 > 代码库 > 黑马程序员-学习日记(生产者消费者实例)
黑马程序员-学习日记(生产者消费者实例)
1 class PCDemo 2 { 3 public static void main(String[] args) 4 { 5 Resource r = new Resource(); 6 Producer prd = new Producer(r); 7 Consumer csu = new Consumer(r); 8 9 Thread th0 = new Thread(prd);10 Thread th1 = new Thread(prd); 11 Thread th2 = new Thread(prd);12 Thread th3 = new Thread(prd);13 14 Thread th4 = new Thread(csu);15 Thread th5 = new Thread(csu);16 Thread th6 = new Thread(csu);17 Thread th7 = new Thread(csu);18 th0.start();19 th1.start();20 th2.start();21 th3.start();22 th4.start();23 th5.start();24 th6.start();25 th7.start();26 }27 }28 29 30 class Resource31 {32 private String name;33 private int count =1;34 private boolean flag = false;35 36 public synchronized void set(String name)37 {38 if(flag)39 try40 {41 wait();42 }43 catch (Exception e)44 {45 }46 this.name = name+"---"+count++;47 System.out.println(Thread.currentThread().getName()+"生產"+this.name);48 flag = true;49 this.notify();50 }51 public synchronized void out()52 {53 if(!flag)54 try55 {56 wait();57 }58 catch (Exception e)59 {60 }61 System.out.println(Thread.currentThread().getName()+"________消費"+this.name);62 flag = false;63 this.notify();64 }65 66 }67 68 class Producer implements Runnable69 {70 private Resource res;71 Producer(Resource res)72 {73 this.res = res;74 }75 public void run()76 {77 while(true)78 {79 res.set("物件");80 }81 }82 }83 84 class Consumer implements Runnable85 {86 private Resource res;87 Consumer(Resource res)88 {89 this.res = res;90 }91 public void run()92 {93 while(true)94 {95 res.out();96 }97 }98 }
黑马程序员-学习日记(生产者消费者实例)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。