作者PTTCATKING (懷念美國貓王)
看板java
標題[問題] 想請問關於JOIN的寫法
時間Mon Nov 10 14:00:17 2014
現在一個流程是這樣
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 就是主程序了說..
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.81.121.136
※ 文章網址: http://www.ptt.cc/bbs/java/M.1415599219.A.31C.html
※ 編輯: PTTCATKING (111.81.121.136), 11/10/2014 14:11:25
※ 編輯: PTTCATKING (111.81.121.136), 11/10/2014 14:12:07
※ 編輯: PTTCATKING (111.81.121.136), 11/10/2014 14:32:28
→ swpoker: concurrent不用嗎~不要再用thread了拉 11/10 15:27
推 nOhiTmE: 如果真的要abcde的話,就用兩個countdown latch。cd共用 11/10 20:50
→ nOhiTmE: 一個,bde共用一個。 11/10 20:50
→ PTTCATKING: 感謝樓上兩位,研究樓上們的推薦,很順利的完成了 11/11 15:26
→ PTTCATKING: 感謝高手的意見提供 11/11 15:27