forked from bage2014/study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadSeqExchange.java
More file actions
88 lines (74 loc) · 1.74 KB
/
Copy pathThreadSeqExchange.java
File metadata and controls
88 lines (74 loc) · 1.74 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
package com.bage.study.java.multhread;
/**
* 多线程交替顺序执行实现
* @author bage
*
*/
public class ThreadSeqExchange {
public static final int count = 1;
public static void main(String[] args) throws Exception {
Print print = new Print();
Thread thread1 = new ThreadSeqEx1(print);
Thread thread2 = new ThreadSeqEx2(print);
// 实现方式
thread1.start();
thread2.start();
}
}
class ThreadSeqEx1 extends Thread{
Print print;
public ThreadSeqEx1(Print print) {
this.print = print;
}
@Override
public void run() {
print.printA();
}
}
class ThreadSeqEx2 extends Thread{
Print print;
public ThreadSeqEx2(Print print) {
this.print = print;
}
@Override
public void run() {
print.printB();
}
}
class Print{
private volatile int orderNum = 1;
public synchronized void printA() {
for (int i = 0; i < 10; i++) {
while(orderNum != 1) {
try {
wait();
// Causes the current thread to wait until another thread invokes the
// java.lang.Object.notify() method or the java.lang.Object.notifyAll() method
// for this object. In other words, this method behaves exactly as
// if it simply performs the call wait(0).
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("A");
orderNum = 2;
notifyAll();
// Wakes up all threads that are waiting on this object's monitor.
// A thread waits on an object's monitor by calling one of the wait methods.
}
}
public synchronized void printB() {
for (int i = 0; i < 10; i++) {
while(orderNum != 2) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("B");
orderNum = 1;
notifyAll();
}
}
}