forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLockWithNewCondition.java
More file actions
89 lines (67 loc) · 2.78 KB
/
Copy pathLockWithNewCondition.java
File metadata and controls
89 lines (67 loc) · 2.78 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
package modern.challenge;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Logger;
public class LockWithNewCondition {
private static final Logger logger
= Logger.getLogger(LockWithNewCondition.class.getName());
private static final ReentrantLock lock = new ReentrantLock();
private static final Condition condition = lock.newCondition();
public void executeByT1() throws InterruptedException {
lock.lock();
try {
logger.info(() -> "Thread " + Thread.currentThread().getName()
+ " waits for 't2' to signal the condition ...");
// When await() is called the thread releases the lock.
// After getting the signal to continue the thread must acquire the lock again.
condition.await();
Thread.sleep(2000);
logger.info(() -> "Thread " + Thread.currentThread().getName()
+ " has finished its execution ...");
} finally {
lock.unlock();
}
}
public void executeByT2() throws InterruptedException {
lock.lock();
try {
logger.info(() -> "Thread " + Thread.currentThread().getName()
+ " signaled the condition ...");
// The condition signal() is triggered. This thread holds the lock,
// therefore 't1' will wait until this thread finishes is tasks.
condition.signal();
Thread.sleep(2000);
logger.info(() -> "Thread " + Thread.currentThread().getName()
+ " has finished its execution ...");
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
System.setProperty("java.util.logging.SimpleFormatter.format",
"[%1$tT] [%4$-7s] %5$s %n");
LockWithNewCondition lockWithNewCondition = new LockWithNewCondition();
Runnable taskT1 = () -> {
try {
lockWithNewCondition.executeByT1();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
logger.severe(() -> "Exception: " + ex);
}
};
Runnable taskT2 = () -> {
try {
lockWithNewCondition.executeByT2();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
logger.severe(() -> "Exception: " + ex);
}
};
Thread t1 = new Thread(taskT1, "t1");
t1.start();
// give time to thread 't1' to acquire the lock
Thread.sleep(2000);
Thread t2 = new Thread(taskT2, "t2");
t2.start();
}
}