如果我在該類中定義了一個類Team
並實現了兩個runnable interfaces
,我不明白任務中的任務由team1
和team2
結束。但是,如果我在WorkerOne
中直接實現runnable
,我會到達打印任務的地方,由WorkerOne
結束。我不明白爲什麼team1
和team2
的任務從未完成,並且應用程序沒有停止。我在下面包含了代碼和控制檯輸出。我會欣賞任何想法或想法。謝謝。無法確定在一個類中的匿名類中實現多個可運行接口時爲什麼CountDownLatch無法正常工作
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class WorkerOne implements Runnable {
private CountDownLatch latch;
public WorkerOne(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
System.out
.println("[Tasks by WorkerOne : ]" + " :: " + "[" + Thread.currentThread().getName() + "]" + " START");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
System.out.println("[Tasks by WorkerOne : ]" + " :: " + "[" + Thread.currentThread().getName() + "]" + " END");
}
}
class Team {
private CountDownLatch latch;
Runnable team1 = new Runnable() {
public void run() {
System.out.println("[Tasks by team1: ]" + " :: " + "[" + Thread.currentThread().getName() + "]" + "START");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
System.out.println("[Tasks by team1 : ]" + " :: " + "[" + Thread.currentThread().getName() + "]" + " END");
}
};
Runnable team2 = new Runnable() {
public void run() {
System.out.println("[Tasks by team2 : ]" + " :: " + "[" + Thread.currentThread().getName() + "]" + "START");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
System.out.println("[Tasks by team2 : ]" + " :: " + "[" + Thread.currentThread().getName() + "]" + " END");
}
};
}
public class Demo {
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(3);
ExecutorService service = Executors.newFixedThreadPool(3);
service.submit(new WorkerOne(latch));
service.submit(new Team().team1);
service.submit(new Team().team2);
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Tasks completed......");
}
}
控制檯輸出爲:
[Tasks by WorkerOne : ] :: [pool-1-thread-1] START
[Tasks by team1: ] :: [pool-1-thread-2]START
[Tasks by team2 : ] :: [pool-1-thread-3]START
[Tasks by WorkerOne : ] :: [pool-1-thread-1] END