forked from ZHENFENG13/concurrent-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimeLock.java
More file actions
44 lines (39 loc) · 1.16 KB
/
TimeLock.java
File metadata and controls
44 lines (39 loc) · 1.16 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
package chapter3;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by 13 on 2017/5/5.
*/
public class TimeLock implements Runnable {
public static ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
try {
if (lock.tryLock(5, TimeUnit.SECONDS)) {
System.out.println(Thread.currentThread().getName());
System.out.println("get lock success");
Thread.sleep(6000);
} else {
System.out.println(Thread.currentThread().getName());
System.out.println("get lock failed");
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}
/**
* ËøÉêÇëµÈ´ýÏÞʱtryLock
* @param args
*/
public static void main(String args[]) {
TimeLock timeLock = new TimeLock();
Thread thread1 = new Thread(timeLock);
Thread thread2 = new Thread(timeLock);
thread1.start();
thread2.start();
}
}