多个生产者/一个消费者:

  

 /**
* 生产者
*/
public class P { private MyStack stack; public P(MyStack stack) {
this.stack = stack;
} public void pushService() {
stack.push();
}
}
 /**
* 消费者
*/
public class C { private MyStack stack; public C(MyStack stack) {
this.stack = stack;
} public void popService() {
System.out.println("pop = " + stack.pop());
}
}
 /**
* 模拟栈
*/
public class MyStack {
private List<Object> list = new ArrayList<>(); public synchronized void push() {
try {
while(list.size() == 1) {
this.wait();
}
list.add(""+Math.random());
this.notifyAll();
System.out.println("push:" + list.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
} public synchronized String pop() {
String value = "";
try {
while(list.size() == 0) {
System.out.println("pop 操作中:" + Thread.currentThread().getName() + "wait状态");
this.wait();
}
value = ""+list.get(0);
list.remove(0);
this.notifyAll();
System.out.println("pop:" + list.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
return value;
}
}
 /**
* 生产者线程
*/
public class P_Thread extends Thread { private P p; public P_Thread(P p) {
this.p = p;
} @Override
public void run() {
while (true) {
p.pushService();
}
}
}
 /**
* 消费者线程
*/
public class C_Thread extends Thread { private C c; public C_Thread(C c) {
this.c = c;
} @Override
public void run() {
while (true) {
c.popService();
}
}
}
 /**
* 测试类
*/
public class Run { public static void main(String[] args) {
MyStack stack = new MyStack();
P p1 = new P(stack);
P p2 = new P(stack);
P p3 = new P(stack);
C c1 = new C(stack); P_Thread pThread1 = new P_Thread(p1);
P_Thread pThread2 = new P_Thread(p2);
P_Thread pThread3 = new P_Thread(p3);
C_Thread cThread1 = new C_Thread(c1); pThread1.start();
pThread2.start();
pThread3.start();
cThread1.start();
}
}

运行结果如下:

  

最新文章

  1. VMware下对虚拟机Ubuntu14系统所在分区sda1进行磁盘扩容
  2. Spring学习记录(十四)---JDBC基本操作
  3. Android 在地图上画矩形
  4. 《Microsoft SQL Server 2008 Internals》读书笔记
  5. NABC竞争性需求分析
  6. Posix线程编程指南(4) 线程终止
  7. 窥探EasyMock(2)进阶使用篇
  8. medoo数据库插入的问题
  9. escape和unescape给字符串编码
  10. phpmyadmin出现空password登录被禁止
  11. 编写CodeMirror Modes详解
  12. Android-Tab
  13. SSM项目思路整合NEW
  14. linux关机、重启命令
  15. LeetCode 905 Sort Array By Parity 解题报告
  16. [BZOJ 4763]雪辉
  17. Java基础-hashMap原理剖析
  18. nyoj 1237 简单dfs
  19. 为什么java代码中要避免多层深度for循环嵌套
  20. Kafka技术原理

热门文章

  1. c语言描述的顺序栈实现
  2. linux系统命令与常识
  3. Question20180106 Java环境变量的配置及为什么要配置环境变量
  4. Oracle单行函数用法
  5. oracle-sql脚本导出EXCEL数据
  6. Mac iOS 允许从任何来源下载应用并打开
  7. 【TOJ 3369】CD(二分)
  8. Maven 运行启动时****找不到符号*com.xxx.user.java
  9. XAMPP中的MySQL与本地MySQL冲突的问题
  10. 【c学习-13】