-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWaitLockTest.java
More file actions
57 lines (51 loc) · 1.61 KB
/
WaitLockTest.java
File metadata and controls
57 lines (51 loc) · 1.61 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
public class WaitLockTest
{
public static void main(String[] args) throws InterruptedException
{
final Object obj = new Object();
final long startTime = System.currentTimeMillis();
new Waiter(obj, "first", startTime).start();
Thread.sleep(100);
new Waiter(obj, "second", startTime).start();
Thread.sleep(15000);
synchronized (obj)
{
obj.notifyAll();
}
}
}
class Waiter extends Thread
{
private final Object lock;
private final long startTime;
public Waiter(Object lock, String name, long startTime)
{
super(name);
this.lock = lock;
this.startTime = startTime;
}
@Override
public void run()
{
System.out.println("Starting running at: " + getTimeAndName());
synchronized (lock)
{
System.out.println("Going to sleep for 3 sec at: " + getTimeAndName());
try
{
Thread.sleep(3000);
System.out.println("After sleep at: " + getTimeAndName());
System.out.println("Now going to wait. " + getTimeAndName());
lock.wait();
System.out.println("Back from wait at: " + getTimeAndName());
Thread.sleep(2000);
}
catch (InterruptedException e) {}
System.out.println("Now done! " + getTimeAndName());
}
}
private String getTimeAndName()
{
return String.format("%d, Thread: %s", System.currentTimeMillis() - startTime, getName());
}
}