forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockedThread.java
More file actions
46 lines (37 loc) · 1.31 KB
/
Copy pathBlockedThread.java
File metadata and controls
46 lines (37 loc) · 1.31 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
package modern.challenge;
public class BlockedThread {
public void blockedThread() {
Thread t1 = new Thread(new SyncCode());
Thread t2 = new Thread(new SyncCode());
t1.start();
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
// log ex
}
t2.start();
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
// log ex
}
System.out.println("BlockedThread t1: " + t1.getState() + "(" + t1.getName() + ")");
System.out.println("BlockedThread t2: " + t2.getState() + "(" + t2.getName() + ")");
System.exit(0);
}
private static class SyncCode implements Runnable {
@Override
public void run() {
System.out.println("Thread " + Thread.currentThread().getName() + " is in run() method");
syncMethod();
}
public static synchronized void syncMethod() {
System.out.println("Thread " + Thread.currentThread().getName() + " is in syncMethod() method");
while (true) {
// t1 will stay here forever, therefore t2 is blocked
}
}
}
}