如果我定义一个类Team
并在该类中实现两个runnable interfaces
,我不会在程序中到达任务结束的team1
点team2
。但是,如果我runnable
直接在类中实现WorkerOne
,我会在它结束时打印任务的位置WorkerOne
。我不明白为什么任务永远不会完成team1
并且team2
应用程序没有停止。我在下面的控制台输出中包含了代码。我会感激任何想法或想法。谢谢你。
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