java生产者消费者模式代码

Java代码 复制代码 收藏代码
  1. package org.hkw.multithread;
  2. public class ThreadDCTest {
  3. public static void main(String[] args) {
  4. Thread p = new Thread(new Producer("p1"));
  5. Thread p2 = new Thread(new Producer("p2"));
  6. Thread c = new Thread(new Consumer("c1"));
  7. Thread c2 = new Thread(new Consumer("c2"));
  8. p.start();
  9. p2.start();
  10. c.start();
  11. c2.start();
  12. try {
  13. Thread.sleep(1000);
  14. } catch (InterruptedException e) {
  15. // TODO Auto-generated catch block
  16. e.printStackTrace();
  17. }
  18. // Storehouse.getInstance().close();
  19. p.interrupt();
  20. p2.interrupt();
  21. c.interrupt();
  22. c2.interrupt();
  23. }
  24. }
  25. class Storehouse {
  26. static final int STATUS_EMPETY = 0;
  27. static final int STATUS_FULL = 1;
  28. boolean isClosed = false;
  29. String item;
  30. int status;
  31. private static Storehouse house = new Storehouse();
  32. private Storehouse() {
  33. }
  34. public static Storehouse getInstance() {
  35. return house;
  36. }
  37. public String getItem() {
  38. status = STATUS_EMPETY;
  39. return item;
  40. }
  41. public void setItem(String item) {
  42. status = STATUS_FULL;
  43. this.item = item;
  44. }
  45. public int getStatus() {
  46. return status;
  47. }
  48. public boolean isEmpty() {
  49. return status == STATUS_EMPETY;
  50. }
  51. public boolean isClosed() {
  52. return isClosed;
  53. }
  54. public void close() {
  55. isClosed = true;
  56. }
  57. public synchronized void produce(String name) throws InterruptedException
  58. {
  59. if (isEmpty()) {
  60. String item = name + " fill";
  61. System.out.println(name + " produce item:" + item);
  62. setItem(item);
  63. notifyAll();
  64. } else {
  65. wait();
  66. }
  67. }   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值