forked from lihengming/java-codes
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUnsafeLock.java
More file actions
34 lines (27 loc) · 746 Bytes
/
Copy pathUnsafeLock.java
File metadata and controls
34 lines (27 loc) · 746 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
32
33
34
package unsafe;
import sun.misc.Unsafe;
import java.lang.reflect.Constructor;
/**
* Created by 李恒名 on 2017/6/21.
*/
public class UnsafeLock {
private Unsafe unsafe;
public UnsafeLock() {
try {
//获得Unsafe的构造器
Constructor<Unsafe> constructor = Unsafe.class.getDeclaredConstructor();
//突破私有访问权限
constructor.setAccessible(true);
//创建示例
this.unsafe = constructor.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
public void lock(Object obj) {
unsafe.monitorEnter(obj);
}
public void unlock(Object obj) {
unsafe.monitorExit(obj);
}
}