java除了提供鎖以外,還提供了一些輔助的同步器。html
1、CountDownLatchjava
做用:經常要有一個線程(master)作彙總,等n個子步驟(線程slave)完成後才能繼續操做。用join寫只能等子線程完成,並且寫起來麻煩;用wait來寫也不是那麼容易。 ui
import java.util.concurrent.CountDownLatch; public class TestThread extends Thread{ private static final int N=5; //指定須要完成的countDown次數 private static CountDownLatch count=new CountDownLatch(N); public static void main(String[] args) throws InterruptedException{ TestThread ts[]=new TestThread[5]; for(int i=0;i<N;i++){ ts[i]= new TestThread(i); ts[i].start(); } //等待N次countDown count.await(); int total=0; for(int i=0;i<N;i++) total+=ts[i].getOut(); System.out.print(total); } private int in; private int out; public TestThread(int in){ this.in=in; } public void run(){ try { out=in*in; Thread.sleep(1000); //完成子任務,彙報 count.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } public int getOut(){ return out; } }
2、CyclicBarrierthis
做用:最直接的做用是n個線程都完成某步操做後才繼續。spa
CountDownLatch是一我的等N我的,就像老師收試卷,你們交卷就跑了,老師要等齊全部試卷後才能走;線程
CyclicBarrier就是N我的互等,就像去春遊,要等到最後一我的到了,你們才能出發。code
然而這只是最直接的功能,CyclicBarrier徹底能夠取代CountDownLatch,並且功能更靈活(能夠重置計數)。你能夠把它當作一個計數器,能想到的一些操做:htm
N個一組地處理一件事。blog
語法參考:http://www.cnblogs.com/skywang12345/p/3533995.html資源
3、Semaphore(信號量)
做用:限制同時訪問特定資源的數量,好比同時讓5個線程同時上傳文件。
public class TestThread { public static void main(String[] args) throws InterruptedException{ final int THREAD_COUNT =10; for(int i =0 ;i < THREAD_COUNT;i++){ Thread t= new Thread(new Task1()); t.start(); } } } class Task1 implements Runnable{ //用信號量設置最多5個線程同時訪問資源 private static Semaphore s =new Semaphore(5); public void run() { try { s.acquire(); System.out.println("upload file"); Thread.sleep(1000); s.release(); } catch (InterruptedException e) { e.printStackTrace(); } } }
4、Exchanger
做用:主要用於線程間交換數據