Guest User

Untitled

a guest
Oct 16th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 KB | None | 0 0
  1. package com.isea.data;
  2.  
  3. /**
  4. * 线程操作资源类
  5. * 判断,干活,唤醒
  6. * 虚假唤醒
  7. *
  8. * 生产者消费者问题,交替消费和生产,两个生产者,两个消费者
  9. */
  10.  
  11. class ShareData{
  12. private int data = 0;
  13.  
  14. public synchronized void produce() throws InterruptedException {
  15. while (data != 0){
  16. this.wait();
  17. }
  18. data ++;
  19. System.out.println(Thread.currentThread().getName() + "生产了,余量\t" + data);
  20. this.notifyAll();
  21. }
  22.  
  23. public synchronized void consumer() throws InterruptedException {
  24. while (data == 0){
  25. this.wait();
  26. }
  27.  
  28. data --;
  29. System.out.println(Thread.currentThread().getName() + "消费了,余量\t" + data);
  30. this.notifyAll();
  31. }
  32. }
  33.  
  34. public class ProduceAndConsumer {
  35. public static void main(String[] args) {
  36. ShareData shareData = new ShareData();
  37. new Thread(() -> {
  38. for (int i = 0; i < 5; i++) {
  39. try {
  40. shareData.produce();
  41. } catch (InterruptedException e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. },"Producer1").start();
  46.  
  47. new Thread(() -> {
  48. for (int i = 0; i < 5; i++) {
  49. try {
  50. shareData.consumer();
  51. } catch (InterruptedException e) {
  52. e.printStackTrace();
  53. }
  54. }
  55. },"Consumer1").start();
  56.  
  57. new Thread(() -> {
  58. for (int i = 0; i < 5; i++) {
  59. try {
  60. shareData.produce();
  61. } catch (InterruptedException e) {
  62. e.printStackTrace();
  63. }
  64. }
  65. },"Producer2").start();
  66.  
  67. new Thread(() -> {
  68. for (int i = 0; i < 5; i++) {
  69. try {
  70. shareData.consumer();
  71. } catch (InterruptedException e) {
  72. e.printStackTrace();
  73. }
  74. }
  75. },"Consumer2").start();
  76. }
  77.  
  78.  
  79. }
  80. /*
  81. Producer1生产了,余量 1
  82. Consumer1消费了,余量 0
  83. Producer1生产了,余量 1
  84. Consumer1消费了,余量 0
  85. Producer1生产了,余量 1
  86. Consumer1消费了,余量 0
  87. Producer1生产了,余量 1
  88. Consumer1消费了,余量 0
  89. Producer1生产了,余量 1
  90. Consumer1消费了,余量 0
  91. Producer2生产了,余量 1
  92. Consumer2消费了,余量 0
  93. Producer2生产了,余量 1
  94. Consumer2消费了,余量 0
  95. Producer2生产了,余量 1
  96. Consumer2消费了,余量 0
  97. Producer2生产了,余量 1
  98. Consumer2消费了,余量 0
  99. Producer2生产了,余量 1
  100. Consumer2消费了,余量 0
  101. */
Add Comment
Please, Sign In to add comment