并发包体系结构:
1. CountDownLatch
CountDownLatch 是一个同步工具类,用来协调多个线程之间的同步。
CountDownLatch 通过计数器来实现:使一个线程在等待另外一些线程完成各自工作后,再执行。计数器初始值为线程的数量。当每一个线程完成自己任务后,就通过 countDown()方法 将计数器减1。当计数器的值减为0时,表示其他所有线程都已经完成了各自的一些任务,然后在 CountDownLatch 上等待的线程就可以恢复执行接下来的任务。
方法源码:
/* @param count the number of times {@link #countDown} must be invoked
* before threads can pass through {@link #await}
* @throws IllegalArgumentException if {@code count} is negative
*/
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
/* Causes the current thread to wait until the latch has counted down to
* zero, unless the thread is {@linkplain Thread#interrupt interrupted}.
* @throws InterruptedException if the current thread is interrupted
* while waiting */
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
/**
* Causes the current thread to wait until the latch has counted down to
* zero, unless the thread is {@linkplain Thread#interrupt interrupted},
* or the specified waiting time elapses. */
public boolean await(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
示例:
public class Test {
public static void main(String[] args) throws InterruptedException {
ThreadPoolExecutor executor = new ThreadPoolExecutor(3,3,10, TimeUnit.SECONDS,new LinkedBlockingDeque<Runnable>());
CountDownLatch latch = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
executor.execute(new Runnable() {
@Override
public void run() {
System.out.println("子线程" + Thread.currentThread().getName() + "开始执行");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("子线程"+Thread.currentThread().getName()+"执行完成");
latch.countDown(); //当前线程调用此方法,计数减一
}
});
}
{
System.out.println("主线程" + Thread.currentThread().getName() + "等待子线程执行完成...");
latch.await();//阻塞当前线程,直到计数器的值为0
System.out.println("主线程" + Thread.currentThread().getName() + "开始执行...");
}
}
}
等待超时:如果某一个线程的操作耗时非常长或者发生了异常. * 但是并不想影响主线程的继续执行, 则可以使用await(long, TimeUnit)方法
2. Atomic原子类
Atomic包下装的是原子类,通过“原子性”操作实现变量在多线程下的线程安全。
如果对变量进行加锁也可以保证线程安全,但抢不到锁线程会发生阻塞,线程上下文的切换会带来些许时延。
Atomic原子类的原理是通过CAS机制不断自旋,
未完待续~