我有四个线程正在运行,我想在它们全部完成时抛出一个标志。我想要做的是将一个 int 设置为 0。当线程完成时,它将为该 int 加 1。最后我将有一个 if 语句,其条件是 int 必须等于 4。当发生这种情况时,将显示一条消息,指示所有线程都已完成。然而,当我尝试这样做时,它说整数必须是最终的或有效的最终的。我该如何解决这个问题?
最佳答案
最简单的方法就是使用Thread.join()
:
Thread[] ts = new Thread[4];
for (int i = 0; i < 4; ++i) {
ts[i] = new Thread(...);
ts[i].start();
}
for (int i = 0; i < ts.length; ++i) {
ts[i].join(); // Wait for the i-th thread to die.
}
在其他替代方案中,您可以使用 CountdownLatch
,它为您在线程何时被视为“完成”方面提供了更大的灵 active :
Thread[] ts = new Thread[4];
final CountdownLatch latch = new CountdownLatch(ts.length);
for (int i = 0; i < 4; ++i) {
ts[i] = new Thread(new Runnable() {
@Override public void run() {
// ...
latch.countDown();
}
});
ts[i].start();
}
latch.await(); // Blocks until all threads have called `countDown()`.
关于java - 如何在java中的线程之间传递整数/其他变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35320043/