Consider I have a run method as below, I am trying to create four threads for MyThread. Statement 1 to 3 can either run at same time by threads or differently. But I want Statement 4 to be executed by threads at a same time. Can I pool all threads before statement 4 and execute statement 4 at a same time by all threads?
class MyThread extends Thread
{
public void run()
{
//Statement 1
//Statement 2
//Statement 3
//Statement 4
}
}
Use CyclicBarrier, it is best suited for your requirement.
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierUsage {
private static final int NUMBER_OF_THREADS = 2;
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(NUMBER_OF_THREADS);
Thread t1 = new Thread(new PrimaryParty(barrier));
Thread t2 = new Thread(new PrimaryParty(barrier));
t1.start();
t2.start();
}
}
class PrimaryParty implements Runnable {
private CyclicBarrier barrier;
public PrimaryParty(CyclicBarrier barrier) {
this.barrier = barrier;
}
@Override
public void run() {
//Statement 1
//Statement 2
//Statement 3
try {
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
//Statement 4
}
}
There are a few ways to do what you want. Perhaps the easiest way is by using Java's implementation of Future . You can define one (or more) Futures which will execute on separate threads, block until they are all done with Future.get() , and then complete your other tasks based on the results.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.