forked from lihengming/java-codes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnsafeLockTest.java
More file actions
46 lines (39 loc) · 1.09 KB
/
Copy pathUnsafeLockTest.java
File metadata and controls
46 lines (39 loc) · 1.09 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
package unsafe;
/**
* Created by 李恒名 on 2017/6/21.
*/
public class UnsafeLockTest {
public static void main(String[] args) {
TestTask test = new TestTask();
new Thread(() -> test.method1()).start();
new Thread(() -> test.method2()).start();
/**
输出:
method1() execute!
method2() execute!
不加锁保持同步:
method2() execute!
method1() execute!
*/
}
static class TestTask {
private UnsafeLock lock = new UnsafeLock();
public void method1() {
lock.lock(this);
try {
//模拟方法需要执行100毫秒
Thread.sleep(100);
System.out.println("method1() execute!");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock(this);
}
}
public void method2() {
lock.lock(this);
System.out.println("method2() execute!");
lock.unlock(this);
}
}
}