[問題] 想請問關於JOIN的寫法

作者: PTTCATKING (懷念美國貓王)   2014-11-10 14:00:17
現在一個流程是這樣
Thread A 執行完成之後,分成兩條Thread,同時執行 B跟 C
然後C這條線執行完後,會再執行D
等到B這條線跟 C&D這條線兩條都跑完後,才開始執行E
如果像是我以下這種寫法,算是 B跟 CD跑完之後,才開始跑E嗎
那一開始起頭的 A 我要怎麼寫呢
public void execute(TaskExecutionContext executor) throws RuntimeException {
System.out.println("Thread E ");
Thread threadB = new Thread(new Runnable() {
public void run() {
try {
System.out.println("Thread B 開始..");
for(int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("Thread B 執行..");
}
System.out.println("Thread B 即將結束..");
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
});
Thread threadC = new Thread(new Runnable() {
public void run() {
try {
System.out.println("Thread C 開始..");
for(int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("Thread C 執行..");
}
System.out.println("Thread C 即將結束..");
System.out.println("Thread D 開始..");
for(int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("Thread D 執行..");
}
System.out.println("Thread D 即將結束..");
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
});
threadB.start();
threadC.start();
try {
// Thread B 加入 Thread A
threadB.join();
threadC.join();
}
catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread E 執行");
for (int i = 1; i <= 30; i++) {
System.out.println("Task 1 says: " + i + executor);
executor.setStatusMessage("第一個任務執行到第 " + i + " 個");
executor.setCompleteness(i / 30D);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
;
}
executor.pauseIfRequested();
if (executor.isStopped()) {
break;
}
}
}
格式可能有點跑掉,這是 讓E等待 B跟CD的寫法
怎麼寫成從A開始呢
因為 E 就是主程序了說..
作者: swpoker (swpoker)   2014-11-10 15:27:00
concurrent不用嗎~不要再用thread了拉
作者: nOhiTmE   2014-11-10 20:50:00
如果真的要abcde的話,就用兩個countdown latch。cd共用一個,bde共用一個。
作者: PTTCATKING (懷念美國貓王)   2014-11-11 15:26:00
感謝樓上兩位,研究樓上們的推薦,很順利的完成了感謝高手的意見提供

Links booklink

Contact Us: admin [ a t ] ucptt.com