|
10 | 10 | package com.juc.queue; |
11 | 11 |
|
12 | 12 | import java.util.LinkedList; |
13 | | -import java.util.concurrent.TimeUnit; |
14 | 13 |
|
15 | 14 | public class ProdConsumerSynchronized { |
16 | 15 |
|
17 | 16 | private final LinkedList<String> lists = new LinkedList<>(); |
18 | 17 |
|
19 | | - private final int MAX = 10; // 最多10个元素 |
20 | | - |
21 | | - private int count = 0; |
22 | | - |
23 | 18 | public synchronized void put(String s) { |
24 | | - while (lists.size() == 1) { // 用while怕有存在虚拟唤醒线程 |
| 19 | + while (lists.size() != 0) { // 用while怕有存在虚拟唤醒线程 |
25 | 20 | // 满了, 不生产了 |
26 | 21 | try { |
27 | 22 | this.wait(); |
28 | 23 | } catch (InterruptedException e) { |
29 | 24 | e.printStackTrace(); |
30 | 25 | } |
31 | 26 | } |
32 | | - lists.add(s); // 毕竟所有线程抢这一把锁 |
33 | | - count++; |
34 | | - try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } |
| 27 | + lists.add(s); |
| 28 | + System.out.println(Thread.currentThread().getName() + " " + lists.peekFirst()); |
35 | 29 | this.notifyAll(); // 这里可是通知所有被挂起的线程,包括其他的生产者线程 |
36 | 30 | } |
37 | 31 |
|
38 | | - public synchronized String get() { |
39 | | - String s = null; |
| 32 | + public synchronized void get() { |
40 | 33 | while (lists.size() == 0) { |
41 | 34 | try { |
42 | 35 | this.wait(); |
43 | 36 | } catch (InterruptedException e) { |
44 | 37 | e.printStackTrace(); |
45 | 38 | } |
46 | 39 | } |
47 | | - s = lists.removeFirst(); |
48 | | - count--; |
| 40 | + System.out.println(Thread.currentThread().getName() + " " + lists.removeFirst()); |
49 | 41 | this.notifyAll(); // 通知所有被wait挂起的线程 用notify可能就死锁了。 |
50 | | - return s; |
51 | 42 | } |
52 | 43 |
|
53 | 44 | public static void main(String[] args) { |
54 | 45 | ProdConsumerSynchronized prodConsumerSynchronized = new ProdConsumerSynchronized(); |
| 46 | + |
55 | 47 | // 启动消费者线程 |
56 | | - for (int i = 0; i < 2; i++) { |
57 | | - new Thread(() -> { |
58 | | - for (int j = 0; j < 15; j++) { |
59 | | - System.out.println(Thread.currentThread().getName() + prodConsumerSynchronized.get()); |
60 | | - } |
61 | | - }, "消费者线程ID:" + i).start(); |
| 48 | + for (int i = 0; i < 5; i++) { |
| 49 | + new Thread(prodConsumerSynchronized::get, "ConsA" + i).start(); |
62 | 50 | } |
63 | 51 |
|
64 | | - try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } |
65 | 52 | // 启动生产者线程 |
66 | | - for (int i = 0; i < 2; i++) { |
| 53 | + for (int i = 0; i < 5; i++) { |
| 54 | + int tempI = i; |
67 | 55 | new Thread(() -> { |
68 | | - for (int j = 0; j < 15; j++) { |
69 | | - prodConsumerSynchronized.put(Thread.currentThread().getName() + " 编号:" + j); |
70 | | - } |
71 | | - }, "生产者线程ID:" + i).start(); |
| 56 | + prodConsumerSynchronized.put("" + tempI); |
| 57 | + }, "ProdA" + i).start(); |
72 | 58 | } |
| 59 | + |
| 60 | + |
| 61 | + |
| 62 | + |
| 63 | + |
| 64 | + |
| 65 | + |
| 66 | + |
73 | 67 | } |
74 | 68 | } |
0 commit comments