使用Countdownlatch和執行人沒有得到預期的輸出我很新到Java多線程。努力學習countdownlatch和執行者在Java線程和實施未來下列代碼 -而在Java
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExecutorBasicFramework {
class MyThread extends Thread{
int iCount ; String name;
CountDownLatch latch;
public MyThread(int iCount, String name, CountDownLatch latch) {
super();
this.iCount = iCount;
this.name = name;
this.latch = latch;
}
@Override
public void run() {
for(int i=0;i<10;i++){
System.out.println(name+" Printing .... "+ ++iCount+" L "+latch.getCount());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
latch.countDown();
}
}
public ExecutorBasicFramework() {
createThread();
}
private void createThread() {
ExecutorService exec = Executors.newFixedThreadPool(10);
CountDownLatch latch = new CountDownLatch(10);
for(int i=0;i<10;i++){
MyThread thread = new MyThread(i*10, ""+i,latch);
exec.execute(thread);
try {
latch.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
exec.shutdownNow();
}
public static void main(String[] args) {
new ExecutorBasicFramework();
}
}
輸出結果 -
0 Printing .... 1 L 10
0 Printing .... 2 L 10
0 Printing .... 3 L 10
0 Printing .... 4 L 10
0 Printing .... 5 L 10
0 Printing .... 6 L 10
0 Printing .... 7 L 10
0 Printing .... 8 L 10
0 Printing .... 9 L 10
0 Printing .... 10 L 10
,然後流程就像是一直等下去。 我的預期輸出如上所示,但在打印0之後,它應該輸出1至9的相似輸出,然後程序應該停止。
我覺得countdownlatch在等待,等待其不會增加執行的下一個櫃檯。所以我無法獲得預期的產出。 我期待輸出如下 -
0 Printing .... 1 L 10
0 Printing .... 2 L 10
0 Printing .... 3 L 10
0 Printing .... 4 L 10
0 Printing .... 5 L 10
0 Printing .... 6 L 10
0 Printing .... 7 L 10
0 Printing .... 8 L 10
0 Printing .... 9 L 10
0 Printing .... 10 L 10
1 Printing .... 11 L 9
1 Printing .... 12 L 9
1 Printing .... 13 L 9
1 Printing .... 14 L 9
1 Printing .... 15 L 9
1 Printing .... 16 L 9
1 Printing .... 17 L 9
1 Printing .... 18 L 9
1 Printing .... 19 L 9
1 Printing .... 20 L 9
and So on ...
2 Printing .... 21 L 8
2 Printing .... 22 L 8
2 Printing .... 23 L 8
與鎖的每個遞減計數器,下一個線程池是必須 執行計數至10,然後再次它必須減少鎖 計數器,並再次過程重複,直到線程9完成 相同
請建議一些輸入。
您是否試圖等待所有工作完成?這裏的目標是什麼? – Gray 2013-02-26 17:46:36