我有一个包含以下 (Java) 代码的方法:
doSomeThings();
doSomeOtherThings();
doSomeThings()
创建一些线程,每个线程只会运行有限的时间。问题是我不希望在 doSomeThings()
启动的所有线程完成之前调用 doSomeOtherThings()
。 (此外 doSomeThings()
将调用可能启动新线程等的方法。我不想在所有这些线程完成之前执行 doSomeOtherThings()
。)
这是因为 doSomeThings()
等会将 myObject
设置为 null
,而 doSomeOtherThings()
调用 myObject.myMethod()
并且我不希望 myObject
当时为 null
。
有没有一些标准的方法来做这种事情(在 Java 中)?
最佳答案
您可能想看看 java.util.concurrent
包。特别是,您可能会考虑使用 CountDownLatch
package de.grimm.game.ui;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args)
throws Exception {
final ExecutorService executor = Executors.newFixedThreadPool(5);
final CountDownLatch latch = new CountDownLatch(3);
for( int k = 0; k < 3; ++k ) {
executor.submit(new Runnable() {
public void run() {
// ... lengthy computation...
latch.countDown();
}
});
}
latch.await();
// ... reached only after all threads spawned have
// finished and acknowledged so by counting down the
// latch.
System.out.println("Done");
}
}
显然,这种技术只有在您事先知道 fork 线程的数量的情况下才有效,因为您需要使用该数量初始化锁存器。
另一种方法是使用条件变量,例如:
boolean done = false;
void functionRunInThreadA() {
synchronized( commonLock ) {
while( !done ) commonLock.wait();
}
// Here it is safe to set the variable to null
}
void functionRunInThreadB() {
// Do something...
synchronized( commonLock ) {
done = true;
commonLock.notifyAll();
}
}
您可能需要添加异常处理(InteruptedException
)等。
关于java - 等待线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2580691/