CountDownLatch
CountDownLatch是一个非常实用的多线程控制工具类。下面写了一个小例子
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(3);
for (int i = 0; i < 5; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName());
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
countDownLatch.countDown();
}).start();
}
countDownLatch.await();
System.out.println("执行完毕");
}
}
查看一下 await方法
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
调用 sync(同步工具的方法获得共享锁)。接下来看一下acquireSharedInterruptibly方法
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted()) //判断当前线程是不是中断了 如果中断了抛出异常
throw new InterruptedException();
if (tryAcquireShared(arg) < 0) //尝试去获得一个共享锁
doAcquireSharedInterruptibly(arg);//获取共享锁
}
进入CountDownLatch的tryAcquireShared方法查看获取共享锁的判断实现
protected int tryAcquireShared(int acquires) {//state是一个计数器
return (getState() == 0) ? 1 : -1;//如果计数器为0 线程都已经执行完了,表示不需要阻塞。
//如果不为0线程未执行完毕,必要阻塞
}
看完了判断条件接下来看看如何获取共享锁 AbstractQueuedSynchronizer(AQS)类下的doAcquireSharedInterruptibly
private void doAcquireSharedInterruptibly(int arg)
throws InterruptedException {
final Node node = addWaiter(Node.SHARED); //把共享节点加到队列中
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head) {
int r = tryAcquireShared(arg);
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
failed = false;
return;
}
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
先定义count值 countDownLatch.countDown() 每执行一次,count值减一,countDownLatch.await()让线程等待,当count减少到0时,所有线程一起并发执行。
CyclieBarries
Semaphore信号量
资源有限共享。信号量表示可以使用的资源数量
1 请求资源 acquire (获取许可)
2 使用资源 业务处理
3 释放资源 release
Semaphore 是 synchronized 的加强版,作用是控制线程的并发数量。就这一点而言,单纯的synchronized 关键字是实现不了的。