-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathSleepWithLock.java
More file actions
31 lines (28 loc) · 921 Bytes
/
SleepWithLock.java
File metadata and controls
31 lines (28 loc) · 921 Bytes
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
class StorageThread implements Runnable{
public static Integer counter = 0;
private static final Object LOCK = new Object();
public void run() {
System.out.println("StorageThread started.");
synchronized(LOCK) { // "LOCK" is locked just before the thread goes to sleep
try {
Thread.sleep(5000);
} catch (InterruptedException e) { ... }
}
System.out.println("StorageThread exited.");
}
}
class OtherThread implements Runnable{
public void run() {
System.out.println("OtherThread started.");
synchronized(StorageThread.LOCK) {
StorageThread.counter++;
}
System.out.println("OtherThread exited.");
}
}
public class SleepWithLock {
public static void main(String[] args) {
new Thread(new StorageThread()).start();
new Thread(new OtherThread()).start();
}
}