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

 /**
* 生产者
*/
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 p = new P(stack);
//多个消费者
C c1 = new C(stack);
C c2 = new C(stack);
C c3 = new C(stack); //一个生产者线程
P_Thread pThread = new P_Thread(p);
//多个消费者线程
C_Thread cThread1 = new C_Thread(c1);
C_Thread cThread2 = new C_Thread(c2);
C_Thread cThread3 = new C_Thread(c3); //启动
pThread.start();
cThread1.start();
cThread2.start();
cThread3.start();
}
}

运行结果如下:

  

  

最新文章

  1. C# SaveFileDialog的用法(转载)
  2. KindEditor4.1.10,支持粘贴图片(转载!)
  3. C#中子类与父类的相互转换
  4. OpenMp之sections用法
  5. [itint5]支持删除的后继查询
  6. 06_init()和destroy()方法
  7. IOS开发中摇一摇是怎么实现的
  8. k8s容器的资源限制
  9. PHP+ajax实现二级联动
  10. 给 Linux 系统“减肥”,系统垃圾清理_系统安装与配置管理_Linux Today - Google Chrome
  11. Android 第三课 构建简单的用户界面
  12. jQuery-contextMenu使用教程
  13. Talend 从Excel导入Saleforce数据(二) TMAP是精髓
  14. android开发(36) Android WebView背景设置为透明
  15. 【android】模拟点击某个指定坐标作用在View上
  16. 禅道ZenTao在windows和Lniux下集成安装环境和一键安装方法整理
  17. jqGrid 将行的字变成超连接
  18. jQuery获取input复选框的值
  19. html和java的交互,利用jsBridge开源框架
  20. 生成二维码 加密解密类 TABLE转换成实体、TABLE转换成实体集合(可转换成对象和值类型) COOKIE帮助类 数据类型转换 截取字符串 根据IP获取地点 生成随机字符 UNIX时间转换为DATETIME\DATETIME转换为UNIXTIME 是否包含中文 生成秘钥方式之一 计算某一年 某一周 的起始时间和结束时间

热门文章

  1. 三张图较为好理解JavaScript的原型对象与原型链
  2. UVA 11605 Lights inside a 3d Grid
  3. Agc007_C Pushing Balls
  4. 70. Climbing Stairs Add to List
  5. .NET MVC 异步提交和返回参数
  6. 如何让RESTful支持DEL和PUT
  7. 判断唯一约束是否是唯一的Unique
  8. java继承实例基础
  9. Breaking Good
  10. Java-API:javax.servlet.http.HttpServletRequest