-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWaitNotifyTest.java
More file actions
100 lines (88 loc) · 2.26 KB
/
Copy pathWaitNotifyTest.java
File metadata and controls
100 lines (88 loc) · 2.26 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package ThreadTest.exers;
/* 1. wait(), notify() and notify() all must be used in synchronized block or synchronized method
* 2. notify will release the prev lock.
* 3. wait, notify, notifyAll are all from Object
*
*
* The common and differences between wait && sleep
* common:
* 1) both will stuck the thread
* difference:
* 1) sleep can be used in any cases, but wait() can only be used in synchronized method or block
* 2) Thread.sleep() && Object.wait()
* 3) sleep won't release the monitor but wait() will do
*
*
* */
public class WaitNotifyTest {
public static void main(String[] args) {
Count count = new Count();
Thread t1 = new Thread(count);
Thread t2 = new Thread(count);
t1.setName("甲");
t2.setName("乙");
t1.start();
t2.start();
}
}
class Count implements Runnable{
private int count = 1;
@Override
public void run() {
while (true){
count();
}
}
public synchronized void count(){
notify();
if(count <= 100){
System.out.println(Thread.currentThread().getName() + ": " + count);
count ++;
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/* question about what if we use wait() and notify() in extending Thread way ???
* code is down below
*
* */
//public class WaitNotifyTest {
// public static void main(String[] args) {
// Count t1 = new Count();
// Count count2 = new Count();
//
// t1.setName("甲");
// count2.setName("乙");
//
// t1.start();
// count2.start();
// }
//}
//
//class Count extends Thread{
//
// private static int count = 1;
// @Override
// public void run() {
//
// while (true){
// count();
// }
// }
//
// public synchronized void count(){
//
// if(count <= 100){
// System.out.println(Thread.currentThread().getName() + ": " + count);
// count ++;
// try {
// wait();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// }
}