利用了AtomicInteger的compareAndSet方法
public class CASLock { private AtomicInteger value = new AtomicInteger(); Thread lockThread ; public boolean tryLock() {
if(value.compareAndSet(, )) {
lockThread = Thread.currentThread();
return true;
}else {
return false;
}
} public void unLock() {
if(value.get() == ) {
return;
}
if(lockThread == Thread.currentThread()) {
value.compareAndSet(, );
}
}
} public class CASLockTest { static CASLock lock = new CASLock(); public static void main(String[] args) { IntStream.rangeClosed(, ).forEach(x -> {
new Thread() {
public void run() {
doSomething();
}
}.start();
});
} public static void doSomething() {
try {
if (lock.tryLock()) {
System.out.println(Thread.currentThread().getName() + " get the lock ");
try {
Thread.sleep();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.println(Thread.currentThread().getName() + " can not get the lock ");
}
} finally {
lock.unLock();
} }
}