1 package multithread4;
2
3 /*
4 * 生产者,消费者。
5 *
6 * 多生产者,多消费者的问题。
7 *
8 * if判断标记,只有一次,会导致不该运行的线程运行了。出现了数据错误的情况。
9 * while判断标记,解决了线程获取执行权后,是否要运行!
10 *
11 * notify:只能唤醒一个线程,如果本方唤醒了本方,没有意义。而且while判断标记+notify会产生死锁
12 * notifyAll解决了,本方线程一定会唤醒对方线程
13 *
14 * 死锁 四个线程都等待没有被唤醒也是一种情况,悬挂
15 */
16
17 class Resource2{
18 private String name;
19 private int count = 1;
20 private boolean flag = false;
21 public synchronized void set(String name) {
22
23 /*if*/ while (flag) {
24 try {
25 this.wait();
26 } catch (InterruptedException e) {
27
28 }
29 }
30 this.name = name + count;
31 count++;
32 System.out.println(Thread.currentThread().getName()+"..生产者.."+this.name);
33 flag = true;
34 // notify();
35 notifyAll();
36 }
37 public synchronized void out() {
38 /*if*/ while (!flag) {
39 try {
40 this.wait();
41 } catch (InterruptedException e) {
42
43 }
44 }
45 System.out.println(Thread.currentThread().getName()+"..消费者......"+this.name);
46 flag = false;
47 // notify();
48 notifyAll();//为了解决死锁 将其余三个都唤醒
49 }
50 }
51
52 class Producer implements Runnable{
53 private Resource2 r;
54 public Producer(Resource2 r) {
55 this.r = r;
56 }
57 public void run() {
58 while(true) {
59 r.set("烤鸭");
60 }
61 }
62 }
63 class Consumer implements Runnable{
64 private Resource2 r;
65 public Consumer(Resource2 r) {
66 this.r = r;
67 }
68 public void run() {
69 while(true) {
70 r.out();
71 }
72 }
73 }
74 public class ProducerConsumerDemo {
75
76 public static void main(String[] args) {
77
78 Resource2 r = new Resource2();
79 Producer pro = new Producer(r);
80 Consumer con = new Consumer(r);
81
82 Thread t0 = new Thread(pro);
83 Thread t1 = new Thread(pro);
84 Thread t2 = new Thread(con);
85 Thread t3 = new Thread(con);
86
87 t0.start();
88 t1.start();
89 t2.start();
90 t3.start();
91 }
92
93 }

ProducerConsumerDemo

最新文章

  1. Html.DropDownLis绑定数据库
  2. nubia Z5 mini 小牛 黑砖qhsusb dload修复
  3. POJ1742 Coins[多重背包可行性]
  4. UITextView限制输入文字
  5. lintcode :Binary Tree Preorder Traversal 二叉树的前序遍历
  6. Windows下配置Nginx使之支持PHP(转)
  7. baiduMap 显示所有的marker(在视野里显示所有的)
  8. 如何让asp.net mvc 直接运行mobile页面
  9. MVC应用程序请求密码的功能1
  10. MVC-工作原理
  11. iOS参考工具和资源
  12. JPA 系列教程12-复合主键-2个@Id+@IdClass
  13. 初学servlet之form表单
  14. 万网域名查询API接口
  15. spring-boot-2.0.3源码篇 - 国际化
  16. linux memcached
  17. 兼容ie10及以上css3加载进度动画
  18. ios UrlEncode与UrlDecode
  19. Java基础语法(一 )
  20. linux之nagios安装教程

热门文章

  1. JAVA获取昨天、今天、明天等日期
  2. ubuntu查系统信息及系统服务
  3. C(++)判断文件是否存在
  4. 【LeetCode】417. Pacific Atlantic Water Flow 解题报告(Python & C++)
  5. 【LeetCode】139. Word Break 解题报告(Python & C++)
  6. 【LeetCode】677. Map Sum Pairs 解题报告(Python & C++)
  7. idea使用教程-模板的使用
  8. 一图搞懂Web应用的单点登录
  9. GitForWindows工具集(GitBash命令行)
  10. Python_使用smtplib+email完成邮件发送