实现主线程等待子线程的几种方案
- 通过AQS下的CountDownLatch来实现。
- 通过Thread.join()方法
- 通过LockSupport.park()以及LockSupport.unpark()配合实现
- 通过Object.wait()配合Object.notify()/Obejct.notifyAll()配合实现
基本知道这几种方式,就够了。
不同方式的关系
其中方式1和方式3都是基于AQS;AQS的各个子类实现,比如可重入锁,可重入读写锁、CountDownLatch等,都是通过LockSuppoort.park()实现线程阻塞,然后把线程加入到阻塞队列中去。然后再通过LockSupport.unpark()实现线程的唤醒;
而方式2其实底层实现是基于方式4的,我们看源码就可以看的出来;
/**
* Waits at most {@code millis} milliseconds for this thread to
* die. A timeout of {@code 0} means to wait forever.
*
* <p> This implementation uses a loop of {@code this.wait} calls
* conditioned on {@code this.isAlive}. As a thread terminates the
* {@code this.notifyAll} method is invoked. It is recommended that
* applications not use wait, notify, or
* notifyAll on Thread instances.
*/
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0

最低0.47元/天 解锁文章
617

被折叠的 条评论
为什么被折叠?



