Repository navigation
Expand file tree
/
Copy pathThreadState.java
More file actions
80 lines (69 loc) · 2.05 KB
/
Copy pathThreadState.java
File metadata and controls
80 lines (69 loc) · 2.05 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
package chapter04;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 6-3
*/
public class ThreadState {
private static Lock lock = new ReentrantLock();
public static void main(String[] args) {
new Thread(new TimeWaiting(), "TimeWaitingThread").start();
new Thread(new Waiting(), "WaitingThread").start();
// 使用两个Blocked线程,一个获取锁成功,另一个被阻塞
new Thread(new Blocked(), "BlockedThread-1").start();
new Thread(new Blocked(), "BlockedThread-2").start();
new Thread(new Sync(), "SyncThread-1").start();
new Thread(new Sync(), "SyncThread-2").start();
}
/**
* 该线程不断的进行睡眠
*/
static class TimeWaiting implements Runnable {
@Override
public void run() {
while (true) {
SleepUtils.second(100);
}
}
}
/**
* 该线程在Waiting.class实例上等待
*/
static class Waiting implements Runnable {
@Override
public void run() {
while (true) {
synchronized (Waiting.class) {
try {
Waiting.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
/**
* 该线程在Blocked.class实例上加锁后,不会释放该锁
*/
static class Blocked implements Runnable {
public void run() {
synchronized (Blocked.class) {
while (true) {
SleepUtils.second(100);
}
}
}
}
static class Sync implements Runnable {
@Override
public void run() {
lock.lock();
try {
SleepUtils.second(100);
} finally {
lock.unlock();
}
}
}
}