-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathTimeLock.java
More file actions
31 lines (27 loc) · 828 Bytes
/
Copy pathTimeLock.java
File metadata and controls
31 lines (27 loc) · 828 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
package ch3.s1;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class TimeLock implements Runnable {
public static ReentrantLock lock = new ReentrantLock();
public void run() {
try {
if (lock.tryLock(5, TimeUnit.SECONDS)) {
Thread.sleep(6000);
} else {
System.out.println("Get lock failed");
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if(lock.isHeldByCurrentThread())
lock.unlock();
}
}
public static void main(String [] args){
TimeLock lock1 = new TimeLock();
Thread t1 = new Thread(lock1);
Thread t2 = new Thread(lock1);
t1.start();
t2.start();
}
}