1【BooleanLatch】 当signal调用时,触发所有等待线程
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
class BooleanLatch {
private static class Sync extends AbstractQueuedSynchronizer {
Integer isSignalled() { return getState(); }
@Override
protected int tryAcquireShared(int ignore) {
return isSignalled() != 0 ? 1 : -1;
}
@Override
protected boolean tryReleaseShared(int ignore) {
setState(1);
return true;
}
}
private final Sync sync = new Sync();
public Integer isSignalled() {
return sync.isSignalled();
}
/**
* 释放一个资源
*/
public void signal() {
sync.releaseShared(1);
}
/**
* 等待资源为空
* @throws InterruptedException
*/
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
/**
* boolean latch == countDownLatch 并且 sychronization state 初始化为1
*/
public static void main(String[] args) throws InterruptedException {
BooleanLatch booleanLatch = new BooleanLatch();
new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("before signal ----->" + booleanLatch.isSignalled());
booleanLatch.signal();
System.out.println("signal ----->" + booleanLatch.isSignalled());
}).start();
System.out.println("开始waiting : await ----->" + booleanLatch.isSignalled());
new Thread(()-> {
try {
booleanLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("await1 ----->" + booleanLatch.isSignalled());
}).start();
new Thread(()-> {
try {
booleanLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("await2 ----->" + booleanLatch.isSignalled());
}).start();
}
}
2 【单机多线程互斥锁】对比分布式锁 redisonLock
public class LeeLock {
private static class Sync extends AbstractQueuedSynchronizer {
@Override
protected boolean tryAcquire (int arg) {
//更新加锁次数
return compareAndSetState(0, 1);
}
@Override
protected boolean tryRelease (int arg) {
//清除锁次数
setState(0);
return true;
}
@Override
protected boolean isHeldExclusively () {
//是否被独占
return getState() == 1;
}
}
private Sync sync = new Sync();
public void lock () {
sync.acquire(1);
}
public void unlock () {
sync.release(1);
}
}
public class LeeMain {
static int count = 0;
static LeeLock leeLock = new LeeLock();
public static void main (String[] args) throws InterruptedException {
Runnable runnable = new Runnable() {
@Override
public void run () {
try {
leeLock.lock();
for (int i = 0; i < 1000; i++) {
Thread.sleep(1);
System.out.println(Thread.currentThread().getId()+"---"+count);
count++;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
leeLock.unlock();
}
}
};
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
Thread thread3 = new Thread(runnable);
Thread thread4 = new Thread(runnable);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread1.join();
thread2.join();
thread4.join();
System.out.println(count);
}
}
图示: