一、經過thread.join()方式,注意:若是有多個子線程,須要將所有的線程先start,而後再join。代碼示例以下:html
public class Main
{
public static void main(String[] args)
{
long start = System.currentTimeMillis();
List<Thread> list = new ArrayList<Thread>();
for(int i = 0; i < 5; i++)
{
Thread thread = new TestThread();
thread.start();
list.add(thread);
}
try
{
for(Thread thread : list)
{
thread.join();
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("子線程執行時長:" + (end - start));
}
} java
二、主線程等待多個子線程(CountDownLatch實現)this
CountDownLatch,一個同步輔助類,在完成一組正在其餘線程中執行的操做以前,它容許一個或多個線程一直等待。spa
主要方法線程
public CountDownLatch(int count);code
public void countDown();orm
public void await() throws InterruptedException
htm
構造方法參數指定了計數的次數blog
countDown方法,當前線程調用此方法,則計數減一get
await方法,調用此方法會一直阻塞當前線程,直到計時器的值爲0
示例代碼以下:
public class CountDownLatchDemo { final static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static void main(String[] args) throws InterruptedException { CountDownLatch latch=new CountDownLatch(2);//兩個工人的協做 Worker worker1=new Worker("zhang san", 5000, latch); Worker worker2=new Worker("li si", 8000, latch); worker1.start();// worker2.start();// latch.await();//等待全部工人完成工做 System.out.println("all work done at "+sdf.format(new Date())); } static class Worker extends Thread{ String workerName; int workTime; CountDownLatch latch; public Worker(String workerName ,int workTime ,CountDownLatch latch){ this.workerName=workerName; this.workTime=workTime; this.latch=latch; } public void run(){ System.out.println("Worker "+workerName+" do work begin at "+sdf.format(new Date())); doWork();//工做了 System.out.println("Worker "+workerName+" do work complete at "+sdf.format(new Date())); latch.countDown();//工人完成工做,計數器減一 } private void doWork(){ try { Thread.sleep(workTime); } catch (InterruptedException e) { e.printStackTrace(); } } } }