Repository navigation
Expand file tree
/
Copy pathRun8_allWait.java
More file actions
75 lines (67 loc) · 2.14 KB
/
Copy pathRun8_allWait.java
File metadata and controls
75 lines (67 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.brianway.learning.java.multithread.communication.example8;
/**
* Created by Brian on 2016/4/14.
*/
/**
* P161
* 多生产与多消费,假死
* 只需将Producer和Consumer类中的notify()改为notifyAll()即可让程序一直运行下去
*/
public class Run8_allWait {
public static void main(String[] args) throws InterruptedException {
String lock = new String("");
Producer producer = new Producer(lock);
Consumer consumer = new Consumer(lock);
ThreadP[] pThread = new ThreadP[2];
ThreadC[] cThread = new ThreadC[2];
for (int i = 0; i < 2; i++) {
pThread[i] = new ThreadP(producer);
pThread[i].setName("生产者" + (i + 1));
cThread[i] = new ThreadC(consumer);
cThread[i].setName("消费者" + (i + 1));
pThread[i].start();
cThread[i].start();
}
Thread.sleep(5000);
Thread[] threads = new Thread[Thread.currentThread().getThreadGroup().activeCount()];
Thread.currentThread().getThreadGroup().enumerate(threads);
for (int i = 0; i < threads.length; i++) {
System.out.println(threads[i].getName() + " " + threads[i].getState());
}
}
}
/*
输出:
消费者 消费者1 WAITING了☆
消费者 消费者2 WAITING了☆
生产者 生产者1 RUNNABLE了
生产者 生产者1 WAITING了★
生产者 生产者2 WAITING了★
消费者 消费者1 RUNNABLE了
消费者 消费者1 WAITING了☆
消费者 消费者2 WAITING了☆
main RUNNABLE
Monitor Ctrl-Break RUNNABLE
生产者1 WAITING
消费者1 WAITING
生产者2 WAITING
消费者2 WAITING
----------------------------
生产者 生产者1 RUNNABLE了
生产者 生产者1 WAITING了★
生产者 生产者2 WAITING了★
消费者 消费者1 RUNNABLE了
消费者 消费者1 WAITING了☆
生产者 生产者1 RUNNABLE了
生产者 生产者1 WAITING了★
生产者 生产者2 WAITING了★
消费者 消费者2 RUNNABLE了
消费者 消费者2 WAITING了☆
消费者 消费者1 WAITING了☆
main RUNNABLE
Monitor Ctrl-Break RUNNABLE
生产者1 WAITING
消费者1 WAITING
生产者2 WAITING
消费者2 WAITING
*/