当在一个类中的匿名类中实现多个可运行接口时,java无法确定CountDownLatch为何不起作用
如果我定义了一个类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
# 1 楼答案
{}class的闩锁变量从未初始化。我怀疑您打算,但忘记了,像在
WorkerOne
类中那样进行初始化当在
latch
字段上调用countDown()
时,在发布代码时执行该代码会使Team
可运行程序抛出NullPointerException
。主线程在其CountDownLatch
上永远等待,因为它永远不会倒计时到0