我需要在某个检查点同步一些线程,并且只有在所有线程到达这一点之后,它们才会继续。有没有简单的构造?
for (int v = 0; v < 10; v++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
doFirst();
//checkpoint
doSecond();
} catch (Throwable e) {
e.printStackTrace();
}
}
}).start();
}
答案 0 :(得分:2)
import java.util.concurrent.CountDownLatch;
private CountDownLatch countDownLatch = new CountDownLatch(10)
...
public void run() {
doFirst();
countDownLatch.countDown();
countDownLatch.await();
doSecond();
}
---- OR(少一行代码)----
import java.util.concurrent.CyclicBarrier;
private CyclicBarrier cyclicBarrier= new CyclicBarrier(10)
...
public void run() {
doFirst();
cyclicBarrier.await();
doSecond();
}
答案 1 :(得分:0)
您可以使用锁定对象执行此操作:
Integer threadCount = 10;
for (int i = 0; i < threadCount; i++)
{
new Thread(() ->
{
try
{
doFirst();
synchronized (threadCount)
{
threadCount--;
while (threadCount > 0)
threadCount.wait();
threadCount.notifyAll();
}
doSecond();
}
catch (Exception e) { e.printStackTrace(); }
}).start();
}
// all threads are started, to wait until they've finished, call threadCount.wait();
答案 2 :(得分:0)
如果您知道线程的确切数量,可以使用java.util.concurrent中的CountDownLatch
。
// First initialize latch with your number of threads
CountDownLatch latch = new CountDownLatch(N);
// Then give this instance of latch to each of your threads
// and finally at your checkpoint do
latch.countDown();
latch.await();
这就是全部。
答案 3 :(得分:0)
一种方法是通过公共监视器同步线程:
Object monitor = new Object();
int jobCount = 0;
public void f1(){
for (int v = 0; v < 10; v++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
doFirst();
check();
doSecond();
} catch (Throwable e) {
e.printStackTrace();
}
}
}).start();
}
}
public void sleep(){}
public void check(){
synchronized(monitor){
jobCount++;
if(jobCount==10){
monitor.notifyAll();
return;
}
}
monitor.wait();
}
需要考虑的事项: