public class CasTip {
private static Unsafe unsafe = UnsafeObject.getUnsafe();
int lock = 0;
static long offset;
static {
try {
offset = unsafe.objectFieldOffset(CasTip.class.getDeclaredField("lock"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// 0: sun.reflect.Reflection
// 1: thread.CasTip
System.out.println(sun.reflect.Reflection.getCallerClass(1).getName());
final CasTip target = new CasTip();
new Thread(new Runnable() {
@Override
public void run() {
lock(target);
System.out.println("lock1");
unlock(target);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
lock(target);
System.out.println("lock2");
unlock(target);
}
}).start();
}
public static void lock(Object o) {
for (;;) {
if (unsafe.compareAndSwapInt(o, offset, 0, 1))
break;
}
}
public static void unlock(Object o) {
unsafe.compareAndSwapInt(o, offset, 1, 0);
}
}
Java 自己动手写一个线程锁
最新推荐文章于 2022-11-22 20:37:23 发布