概述
同步工具类可以是任何一个对象, 只要它根据自身的状态来协调线程的控制流.比如阻塞队列, 信号量, 栅栏以及闭锁等.
这些同步工具类都有一些特定的属性:它们封装了一些状态,这些状态将决定执行同步工具类的线程是继续执行还是等待, 还提供了一些方法对状态进行操作,以及一些方法用于高效地等待同步工具进入预期状态.
常见的同步工具类
闭锁(Latch)
设计动机: 延迟线程进度直到其达到终止状态, 闭锁可以确保某些活动直到其他活动都结束之后才继续执行.
设计解释: 闭锁像是一扇门, 在到达结束状态前, 这扇门一直是关着的,任何线程不能通过, 当这扇门的状态达到结束后, 门被打开, 所有的线程都能通过, 而且不再关闭.
常见使用场景:
闭锁使用示例:
/**
* 需求:
* 1. 确保所有的线程都初始化完成之后, 才开始执行.
*
*/
public class CountDownLatchStarter {
/**
* @param threads 线程数
* @param task 任务
* @return 任务一共执行的时间, 毫秒数
*/
private long execTask(int threads, final Runnable task) throws InterruptedException {
final CountDownLatch startState = new CountDownLatch(1);
final CountDownLatch endState = new CountDownLatch(threads);
for (int i = 0; i < threads; i++) {
Thread t = new Thread(() -> {
try {
startState.await();
try {
task.run();
}finally {
endState.countDown();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t.start();
}
long start = System.currentTimeMillis();
startState.countDown();
endState.await();
long end = System.currentTimeMillis();
return end - start;
}
public static void main(String[] args) throws InterruptedException {
Runnable runnable = () ->{
for (int i = 0; i < 50; i++) {
System.out.print("");
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
CountDownLatchStarter starter = new CountDownLatchStarter();
long duration = starter.execTask(10, runnable);
System.out.println("execution duration: " + duration);
}
}
信号量(Semaphore)
设计动机: 控制同时访问某个特定资源的操作数量, 或者同时执行某个指定操作的数量.
设计思路: