wait与notify的使用

简单记录一个Demo(两个线程轮流打印数字,一个打印奇数,一个打印偶数,每打印10个就交换)

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
package org.my.threadPoolDemo;
import java.util.concurrent.CountDownLatch;
public class {
private static final Object syc = new Object();
public static CountDownLatch lat = new CountDownLatch(2);
public static void main(String[] args) {
Runnable R1 = new Runnable() {
public void run() {
int count = 0;
for(int i = 0;i<100;i++) {
if(i%2 == 0) {
System.out.println("偶数:"+i);
count++;
}
if(count == 10) {
try {
synchronized (syc) {
syc.notify();
syc.wait();
}
count = 0;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("偶数结束");
synchronized (syc) {
syc.notify();
}
lat.countDown();
}
};
Runnable R2 = new Runnable() {
public void run() {
int count = 0;
for(int i=0;i<100;i++) {
if(i%2 == 1) {
System.out.println("奇数:"+i);
count++;
}
if(count == 10) {
try {
synchronized (syc) {
syc.notify();
syc.wait();
}
count = 0;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("奇数结束");
synchronized(syc) {
syc.notify();
}
lat.countDown();
}
};
Thread t1 = new Thread(R1);
Thread t2 = new Thread(R2);
t1.start();
t2.start();
try {
lat.await();
System.out.println("两个线程全部结束");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}