生产者消费者模式,并发采用ReentrantLock

来源:互联网 发布:mac怎么玩穿越火线 编辑:程序博客网 时间:2024/06/15 02:40
Java代码 复制代码 收藏代码
  1. package org.hkw.multithread;
  2. import java.util.concurrent.locks.Lock;
  3. import java.util.concurrent.locks.ReentrantLock;
  4. public class ThreadDCTest {
  5. public static void main(String[] args) {
  6. Thread p = new Thread(new Producer("p1"));
  7. Thread p2 = new Thread(new Producer("p2"));
  8. Thread c = new Thread(new Consumer("c1"));
  9. Thread c2 = new Thread(new Consumer("c2"));
  10. p.start();
  11. p2.start();
  12. c.start();
  13. c2.start();
  14. try {
  15. Thread.sleep(1000);
  16. } catch (InterruptedException e) {
  17. // TODO Auto-generated catch block
  18. e.printStackTrace();
  19. }
  20. // Storehouse.getInstance().close();
  21. c.interrupt();
  22. c2.interrupt();
  23. p.interrupt();
  24. p2.interrupt();
  25. }
  26. }
  27. class Storehouse {
  28. static final int STATUS_EMPETY = 0;
  29. static final int STATUS_FULL = 1;
  30. boolean isClosed = false;
  31. String item;
  32. int status;
  33. Lock lock = new ReentrantLock();
  34. private static Storehouse house =new Storehouse();
  35. private Storehouse() {
  36. }
  37. public static Storehouse getInstance() {
  38. return house;
  39. }
  40. public String getItem() {
  41. status = STATUS_EMPETY;
  42. return item;
  43. }
  44. public void setItem(String item) {
  45. status = STATUS_FULL;
  46. this.item = item;
  47. }
  48. public int getStatus() {
  49. return status;
  50. }
  51. public boolean isEmpty() {
  52. return status == STATUS_EMPETY;
  53. }
  54. public boolean isClosed() {
  55. return isClosed;
  56. }
  57. public void close() {
  58. isClosed = true;
  59. }
  60. public void produce(String name)throws InterruptedException {
  61. lock.lockInterruptibly();
  62. try {
  63. if (isEmpty()) {
  64. String item = name + " fill";
  65. System.out.println(name + " produce item:" + item);
  66. setItem(item);
  67. }
  68. } finally {
  69. lock.unlock();
  70. }
  71. }
  72. public void consum(String name)throws InterruptedException {
  73. lock.lockInterruptibly();
  74. try {
  75. if (!isEmpty()) {
  76. System.out.println(name + " consum item:" + house.getItem());
  77. }
  78. } finally {
  79. lock.unlock();
  80. }
  81. }
  82. }
  83. class Producer implements Runnable {
  84. Storehouse house = Storehouse.getInstance();
  85. String name;
  86. public Producer(String name) {
  87. this.name = name;
  88. }
  89. @Override
  90. public void run() {
  91. System.out.println(name + " producer start");
  92. while (!Thread.currentThread().isInterrupted() && !house.isClosed()) {
  93. try {
  94. house.produce(name);
  95. } catch (InterruptedException e) {
  96. // TODO Auto-generated catch block
  97. System.out.println(name + " producer interrupted");
  98. Thread.currentThread().interrupt();
  99. }
  100. }
  101. System.out.println(name + " producer end");
  102. }
  103. }