Skip to content

Commit 9564eda

Browse files
committed
ProdConsumerSynchronized
1 parent 7414fa1 commit 9564eda

1 file changed

Lines changed: 20 additions & 26 deletions

File tree

Multithread/src/com/juc/queue/ProdConsumerSynchronized.java

Lines changed: 20 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -10,65 +10,59 @@
1010
package com.juc.queue;
1111

1212
import java.util.LinkedList;
13-
import java.util.concurrent.TimeUnit;
1413

1514
public class ProdConsumerSynchronized {
1615

1716
private final LinkedList<String> lists = new LinkedList<>();
1817

19-
private final int MAX = 10; // 最多10个元素
20-
21-
private int count = 0;
22-
2318
public synchronized void put(String s) {
24-
while (lists.size() == 1) { // 用while怕有存在虚拟唤醒线程
19+
while (lists.size() != 0) { // 用while怕有存在虚拟唤醒线程
2520
// 满了, 不生产了
2621
try {
2722
this.wait();
2823
} catch (InterruptedException e) {
2924
e.printStackTrace();
3025
}
3126
}
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());
3529
this.notifyAll(); // 这里可是通知所有被挂起的线程,包括其他的生产者线程
3630
}
3731

38-
public synchronized String get() {
39-
String s = null;
32+
public synchronized void get() {
4033
while (lists.size() == 0) {
4134
try {
4235
this.wait();
4336
} catch (InterruptedException e) {
4437
e.printStackTrace();
4538
}
4639
}
47-
s = lists.removeFirst();
48-
count--;
40+
System.out.println(Thread.currentThread().getName() + " " + lists.removeFirst());
4941
this.notifyAll(); // 通知所有被wait挂起的线程 用notify可能就死锁了。
50-
return s;
5142
}
5243

5344
public static void main(String[] args) {
5445
ProdConsumerSynchronized prodConsumerSynchronized = new ProdConsumerSynchronized();
46+
5547
// 启动消费者线程
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();
6250
}
6351

64-
try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
6552
// 启动生产者线程
66-
for (int i = 0; i < 2; i++) {
53+
for (int i = 0; i < 5; i++) {
54+
int tempI = i;
6755
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();
7258
}
59+
60+
61+
62+
63+
64+
65+
66+
7367
}
7468
}

0 commit comments

Comments
 (0)