-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoThread.java
More file actions
99 lines (88 loc) · 2.7 KB
/
TwoThread.java
File metadata and controls
99 lines (88 loc) · 2.7 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
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 两个线程交替执行打印 1~100
*/
public class TwoThread {
private int start = 1;
/**
* 保证内存可见性
* 其实用锁了之后也可以保证可见性 这里用不用 volatile 都一样
*/
private boolean flag = false;
/**
* 重入锁
*/
private final static Lock LOCK = new ReentrantLock();
public static void main(String[] args) {
TwoThread twoThread = new TwoThread();
Thread t1 = new Thread(new EvenNumberThread(twoThread));
t1.setName("t1");
Thread t2 = new Thread(new OddNumberThread(twoThread));
t2.setName("t2");
t1.start();
t2.start();
}
/**
* 偶数线程
*/
public static class EvenNumberThread implements Runnable {
private TwoThread number;
EvenNumberThread(TwoThread number) {
this.number = number;
}
@Override
public void run() {
while (number.start < 100) {
if (number.flag) {
try {
LOCK.lock();
System.out.println(Thread.currentThread().getName() + "+-+" + number.start);
number.start++;
number.flag = false;
} finally {
LOCK.unlock();
}
} else {
try {
//防止线程空转
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
/**
* 奇数线程
*/
public static class OddNumberThread implements Runnable {
private TwoThread number;
OddNumberThread(TwoThread number) {
this.number = number;
}
@Override
public void run() {
while (number.start <= 100) {
if (!number.flag) {
try {
LOCK.lock();
System.out.println(Thread.currentThread().getName() + "+-+" + number.start);
number.start++;
number.flag = true;
} finally {
LOCK.unlock();
}
} else {
try {
//防止线程空转
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}