线程交替打印
重点在wait和notify的协作
交替打印0、1
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
public class PrintZeroOne {
private int count;//0、1切换
private int num;//计数
private final int max;//最大打印次数+1
public PrintZeroOne(int max) {
this.max = max;
}
/**
* 打印0
*/
public synchronized void printZero() {
while (num < max) {
while (count == 1) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "->" + count++);
num++;
this.notify();
}
}
/**
* 打印1
*/
public synchronized void printOne() {
while (num < max) {
while (count == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "->" + count--);
num++;
this.notify();
}
}
public static void main(String[] args) {
PrintZeroOne printZeroOne = new PrintZeroOne(5);
new Thread(() -> {
printZeroOne.printZero();
}, "child").start(); //child线程
printZeroOne.printOne(); //main线程
}
}
结果:
1
2
3
4
5
6
child->0
main->1
child->0
main->1
child->0
main->1
交替打印奇偶数
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
public class PrintOddEven {
private int num;
private int max;
public PrintOddEven(int max) {
this.max = max;
}
/**
* 打印奇数
*/
public synchronized void odd() {
while (num < max) {
while ((num & 1) == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " " + (num++));
notify();
}
}
/**
* 打印偶数
*/
public synchronized void even() {
while (num < max) {
while ((num & 1) == 1) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " " + (num++));
notify();
}
}
public static void main(String[] args) {
PrintOddEven printOddEven = new PrintOddEven(100);
new Thread(() -> {
printOddEven.even();
}, "偶数").start();
new Thread(() -> {
printOddEven.odd();
}, "奇数").start();
}
}
结果:
1
2
3
4
5
6
7
8
偶数 0
奇数 1
偶数 2
奇数 3
偶数 4
奇数 5
偶数 6
.....