使用AtomicInteger写一个显示锁

时间:2024-10-02 12:07:08

利用了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();
} }
}

相关文章