遇到一個(gè)筆試題:5個(gè)線程內(nèi)部打印hello和word所宰,hello在前,要求提供一種方法使得5個(gè)線程先全部打印出hello后再打印5個(gè)word
首先想到的是CountDownLatch畜挥、CyclicBarrier這類線程阻塞工具仔粥,趁此機(jī)會(huì),總結(jié)下這幾個(gè)工具的用法吧蟹但。
1躯泰、CountDownLatch
先看下源碼吧,這是構(gòu)造方法
/**
* Constructs a {@code CountDownLatch} initialized with the given count.
*
* @param count the number of times {@link #countDown} must be invoked
* before threads can pass through {@link #await}
* @throws IllegalArgumentException if {@code count} is negative
*/
public CountDownLatch(int count) {//count為計(jì)數(shù)值
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
還有幾個(gè)主要的方法
public void await() throws InterruptedException {}; //調(diào)用await()方法后線程會(huì)被掛起华糖,等待直到count值為0才繼續(xù)執(zhí)行麦向,除非線程Intercept
public boolean await(long timeout, TimeUnit unit) throws InterruptedException {}; //和await()類似,只不過等待一定的時(shí)間后count值還沒變?yōu)?的話就會(huì)繼續(xù)執(zhí)行
public void countDown() {}; //將count值減1
先寫一個(gè)簡單的例子客叉,比如5個(gè)線程都打印完HelloWorld 后诵竭,打印一條語句
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(5);
for (int i = 0; i < 5; i++) {
new PrintThread(latch, i).start();
}
try {
latch.await();//等待,直到此CountDownLatch里面的count=0
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("******** Print Over ***********");
}
static class PrintThread extends Thread {
CountDownLatch latch;
int id;
public PrintThread(CountDownLatch latch, int id) {
this.latch = latch;
this.id = id;
}
@Override
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Hello World " + id);
this.latch.countDown();//在做完工作后兼搏,countDown減1
}
}
結(jié)果如下
Hello World 0
Hello World 3
Hello World 2
Hello World 1
Hello World 4
******** Print Over ***********
工作線程每次執(zhí)行完后卵慰,countDown()減1,await()掛起向族,先在那等著呵燕,直到count=0的時(shí)候,才繼續(xù)向下執(zhí)行件相。
好了再扭,回到開始的題目氧苍,稍微改下就可以了
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(5);
for (int i = 0; i < 5; i++) {
new PrintThread(latch, i).start();
}
}
static class PrintThread extends Thread {
CountDownLatch latch;
int id;
public PrintThread(CountDownLatch latch, int id) {
this.latch = latch;
this.id = id;
}
@Override
public void run() {
System.out.println("Hello " + id);
this.latch.countDown();
try {
this.latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("World " + id);
}
}
結(jié)果如下
Hello 0
Hello 3
Hello 4
Hello 2
Hello 1
World 1
World 2
World 3
World 4
World 0
同一個(gè)CountDownLatch對象,在線程中泛范,打印完第一條"Hello"語句后让虐,countDown(),然后await()掛起罢荡,count=0的時(shí)候赡突,再向下打印"World" 語句
2、CyclicBarrier
先看下構(gòu)造方法
/**
* Creates a new <tt>CyclicBarrier</tt> that will trip when the
* given number of parties (threads) are waiting upon it, and
* does not perform a predefined action when the barrier is tripped.
*
* @param parties the number of threads that must invoke {@link #await}
* before the barrier is tripped
* @throws IllegalArgumentException if {@code parties} is less than 1
*/
public CyclicBarrier(int parties) {
this(parties, null);
}
/**
* Creates a new <tt>CyclicBarrier</tt> that will trip when the
* given number of parties (threads) are waiting upon it, and which
* will execute the given barrier action when the barrier is tripped,
* performed by the last thread entering the barrier.
*
* @param parties the number of threads that must invoke {@link #await}
* before the barrier is tripped
* @param barrierAction the command to execute when the barrier is
* tripped, or {@code null} if there is no action
* @throws IllegalArgumentException if {@code parties} is less than 1
*/
public CyclicBarrier(int parties, Runnable barrierAction) {
if (parties <= 0) throw new IllegalArgumentException();
this.parties = parties;
this.count = parties;
this.barrierCommand = barrierAction;
}
主要方法是
public int await() throws InterruptedException, BrokenBarrierException {};//掛起當(dāng)前線程区赵,直至所有線程都到達(dá)阻塞狀態(tài)(即所有線程都執(zhí)行到了await方法)再執(zhí)行await后面的任務(wù)惭缰;
public int await(long timeout, TimeUnit unit)throws InterruptedException,BrokenBarrierException,TimeoutException {};//讓這些線程等待至一定的時(shí)間,如果還有線程沒有到達(dá)阻塞狀態(tài)就直接讓已經(jīng)到達(dá)阻塞狀態(tài)的線程執(zhí)行后續(xù)任務(wù)
回到最開始的題目
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
for (int i = 0; i < 5; i++) {
new PrintThread(cyclicBarrier, i ).start();
}
System.out.println("******** Print Main ***********");
}
static class PrintThread extends Thread {
CyclicBarrier cyclicBarrier;
int id;
public PrintThread(CyclicBarrier cyclicBarrier, int id) {
this.cyclicBarrier = cyclicBarrier;
this.id = id;
}
@Override
public void run() {
System.out.println("Hello " + id);
try {
this.cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println("World " + id);
}
}
執(zhí)行結(jié)果如下
Hello 0
******** Print Main ***********
Hello 3
Hello 2
Hello 1
Hello 4
World 0
World 2
World 3
World 4
World 1
在執(zhí)行完打印"Hello"任務(wù)后笼才,調(diào)用CyclicBarrier的await()方法漱受,線程阻塞在這里,等所有線程都await()了骡送,再執(zhí)行以下的任務(wù)昂羡,打印"World"。
另外摔踱,CyclicBarrier第二個(gè)構(gòu)造方法里有一個(gè)Runnable類型的參數(shù)虐先,看下注釋,
// 等阻塞釋放了派敷,再執(zhí)行的指令
@param barrierAction the command to execute when the barrier is tripped
我們用另外一個(gè)構(gòu)造方法試試
CyclicBarrier cyclicBarrier = new CyclicBarrier(5, new Runnable() {
@Override
public void run() {
System.out.println("******** Print Main ***********");
}
});
執(zhí)行結(jié)果如下
Hello 0
Hello 2
Hello 1
Hello 4
Hello 3
******** Print Main ***********
World 3
World 0
World 1
World 2
World 4
所有的"Hello" 打印完蛹批,再執(zhí)行這個(gè)barrierAction參數(shù),而且膀息,需要注意的是般眉,等barrierAction執(zhí)行完畢后,才會(huì)再往下執(zhí)行潜支。
總結(jié)
CountDownLatch甸赃、CyclicBarrier都能實(shí)現(xiàn)線程阻塞,區(qū)別是在使用過程中CountDownLatch調(diào)用await()方法僅實(shí)現(xiàn)阻塞冗酿,對計(jì)數(shù)沒有影響埠对,線程執(zhí)行完需要手動(dòng)countDown()更新計(jì)數(shù),而CyclicBarrier調(diào)用await()方法后裁替,會(huì)統(tǒng)計(jì)是否全部await()了项玛,如果沒有全部await(),就阻塞弱判,也就是說襟沮,CyclicBarrier的await()方法也參與計(jì)數(shù)了;另外一方面,CountDownLatch不能復(fù)用开伏,CyclicBarrier可以在某個(gè)線程中調(diào)用它的reset()方法復(fù)用膀跌。
補(bǔ)充
CountDownLatch、CyclicBarrier和后面要講的Semaphore固灵、JDK 1.6版本的FutureTask都是基于AbstractQueuedSynchronizer機(jī)制實(shí)現(xiàn)同步的捅伤,源碼解析可參考:http://brokendreams.iteye.com/blog/2250372