首页 > 代码库 > 生产者/消费者 模式

生产者/消费者 模式

目的:保证商品不多于20个,不少于0个,且当商品为20个时暂停生产并且通知消费者消费,为0个时则通知消费者无货。
注意点:注意 if 语句的选择(if 放什么、else 放什么)

  1. public class TestProduct {
  2. public static void main(String[] args) {
  3. Clerk clerk = new Clerk();
  4. Consumer con = new Consumer(clerk);
  5. Producer pro = new Producer(clerk);
  6. Thread t1 = new Thread(con);
  7. Thread t2 = new Thread(con);
  8. Thread t3 = new Thread(pro);
  9. Thread t4 = new Thread(pro);
  10. t1.setName("1");
  11. t2.setName("2");
  12. t3.setName("1");
  13. t4.setName("2");
  14. t1.start();
  15. t2.start();
  16. t3.start();
  17. t4.start();
  18. }
  19. }
  20. class Clerk {
  21. int numOfProduction;// 共享資源
  22. public synchronized void produce() {// 定义生产共享资源的方法
  23. if (numOfProduction == 20) {// 达到20个则暂停生产,否则继续生产并且唤醒消费
  24. try {
  25. wait();
  26. } catch (InterruptedException e) {
  27. e.printStackTrace();
  28. }
  29. } else {
  30. try {
  31. Thread.currentThread().sleep(100);
  32. } catch (InterruptedException e) {
  33. e.printStackTrace();
  34. }
  35. numOfProduction++;
  36. System.out.println(Thread.currentThread().getName() + "号生产者生产了货架上第" + numOfProduction + "号产品");
  37. notifyAll();
  38. }
  39. }
  40. public synchronized void consume() {// 定义消费共享资源的方法
  41. if (numOfProduction == 0) {// 达到0个则暂停消费,否则继续消费并且唤醒生产
  42. try {
  43. wait();
  44. } catch (InterruptedException e) {
  45. e.printStackTrace();
  46. }
  47. } else {
  48. try {
  49. Thread.currentThread().sleep(100);
  50. } catch (InterruptedException e) {
  51. e.printStackTrace();
  52. }
  53. System.out.println(Thread.currentThread().getName() + "号消费者消费了货架上第" + numOfProduction + "号产品");
  54. numOfProduction--;
  55. notifyAll();// 已消费,唤醒生产者生产
  56. }
  57. }
  58. }
  59. class Producer implements Runnable {
  60. Clerk clerk;
  61. public Producer(Clerk clerk) {
  62. super();
  63. this.clerk = clerk;
  64. }
  65. @Override
  66. public void run() {
  67. while (true) {
  68. clerk.produce();
  69. }
  70. }
  71. }
  72. class Consumer implements Runnable {
  73. Clerk clerk;
  74. public Consumer(Clerk clerk) {
  75. super();
  76. this.clerk = clerk;
  77. }
  78. @Override
  79. public void run() {
  80. while (true) {
  81. clerk.consume();
  82. }
  83. }
  84. }

生产者/消费者 模式