- CountDownLatch和join的作用类似。
join
Thread.join()方法使线程等待,待线程退出时,调用Thread.join()的主线程会被唤醒,从而执行后续操作。当处于线程池的状态下,线程不会退出,join就会一直执行不到。
- 非线程池如下示例,会先输出“Child thread running”,然后输出 “执行结束”
public class ThreadJoinDemo {
private static class ThreadDemo extends Thread {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Child thread running");
}
}
public static void main(String[] args) throws Exception {
ThreadDemo threadDemo = new ThreadDemo();
Thread thread = new Thread(threadDemo);
thread.start();
thread.join();
System.out.println("执行结束");
}
}
- 线程池如下示例,会先输出“执行结束”,然后输出 “Child thread running”
public class ThreadJoinDemo {
private static class ThreadDemo extends Thread {
@Override
public void run() {
try{
Thread.sleep(1000);
}catch (Exception e) {
e.printStackTrace();
}
System.out.println("Child thread running");
}
}
public static void main(String[] args)throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(1);
ThreadDemo threadDemo = new ThreadDemo();
executorService.execute(threadDemo);
threadDemo.join();
System.out.println("执行结束");
}
CountDownLatch
countDownLatch方法
//构造函数 count为计数器
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
//调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
//和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行
public boolean await(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
//将count值减1
public void countDown() {
sync.releaseShared(1);
}
CountDownLatch即可解决上述join问题。 如下示例,会优先输出 Child thread running,然后输出 “主线程执行结束”
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(1);
Executor executor = Executors.newFixedThreadPool(1);
executor.execute(new Runnable() {
@Override
public void run() {
try{
Thread.sleep(1000);
}catch (Exception e) {
e.printStackTrace();
}
System.out.println("Child thread running");
countDownLatch.countDown();
}
});
countDownLatch.await();
System.out.println("主线程线程执行结束");
}
}