TestLock.class
public class TestLock {
private static Unsafe unsafe;
private static long valueOffset;
private volatile int value = 0;
static {
try {
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
unsafe = (Unsafe) theUnsafe.get(null);
valueOffset = unsafe.objectFieldOffset
(TestLock.class.getDeclaredField("value"));
System.out.println("valueOffset:" + valueOffset);
} catch (Exception ex) { throw new Error(ex); }
}
public void lock(){
for (;;){
if (unsafe.compareAndSwapInt(this ,valueOffset,0,1)){
System.out.println(Thread.currentThread().getName()+" lock");
return;
}
}
}
public void unLock(){
value = 0;
System.out.println(Thread.currentThread().getName()+" unLock");
}
}
public static void main(String[] args) {
TestLock testLock = new TestLock();
ExecutorService executorService = Executors.newFixedThreadPool(10);
for (;;){
executorService.execute(new Runnable() {
@Override
public void run() {
testLock.lock();
System.out.println(Thread.currentThread().getName()+" run");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
testLock.unLock();
}
});
}
}

被折叠的 条评论
为什么被折叠?



