1、使用join
public class TestCountDownLatch2
{
public static void main(String[] args) throws InterruptedException
{
Thread[] threadArr = new Thread[10];
for(int i = 0; i < 10; i++){
threadArr[i] = new Thread(new WorkThread());
}
for(int i=0;i<10;i++){
threadArr[i].start();
}
for(int i=0;i<10;i++){
threadArr[i].join();
}
System.out.println("main done!");
}
}
class WorkThread implements Runnable {
@Override
public void run()
{
System.out.println(Thread.currentThread().getName() + " worked");
}
}
2、使用ExecutorService.isTerminated死循环判断
public class TestCountDownLatch
{
public static void main(String[] args) throws InterruptedException
{
ExecutorService executorService = Executors.newCachedThreadPool();
for(int i = 0; i < 10; i++){
executorService.execute(new Thread(new WorkThread()));
}
System.out.println("submit all task");
executorService.shutdown(); // stop accept new task
while(!executorService.isTerminated()){ // must call shutdown first, when before tasks finished, then the flag is set true
; // do nothing
}
System.out.println("main thread done!");
}
}
class WorkThread implements Runnable {
@Override
public void run()
{
System.out.println(Thread.currentThread().getName() + " worked");
try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
3、使用CountDownLatch
特点:CountDown方法可以用在任何地方,可以是N个线程,也可以是1个线程里的N个执行步骤
public class TestCountDownLatch2
{
public static void main(String[] args) throws InterruptedException
{
CountDownLatch countDownLatch = new CountDownLatch(10);
ExecutorService executorService = Executors.newCachedThreadPool();
for(int i = 0; i < 10; i++){
executorService.execute(new Thread(new WorkThread(countDownLatch)));
}
System.out.println("submit all task");
executorService.shutdown(); // stop accept new task
countDownLatch.await(); // wait until the latch has count down to zero
System.out.println("main done!");
}
}
class WorkThread implements Runnable {
private CountDownLatch countDownLatch;
public WorkThread(CountDownLatch countDownLatch){
this.countDownLatch = countDownLatch;
}
@Override
public void run()
{
System.out.println(Thread.currentThread().getName() + " worked");
countDownLatch.countDown();
}
}
比较总结:
join用于让当前执行线程等待join线程执行结束。其实现原理是不停检查join线程是否存活,如果join线程存活则让当前线程永远wait,直到join线程中止后,线程的this.notifyAll会被调用
JDK不推荐在线程实例上使用wait,notify和notifyAll方法
推荐使用CountDownLatch