Reputation: 93
I have say two threads t1 and t2 which I want to start at the same time (simultaneously), each call System.out.println()
to print to console, and then to finish at the same time.
Please advise how to achieve this can it be achieve through executor framework. I am trying to do it with the help of executor framework itself..!!
Upvotes: 0
Views: 104
Reputation: 328785
You can either use 2 CountDownLatch
es or a CyclicBarrier
to do that. For example:
final CountDownLatch start = new CountDownLatch(2);
final CountDownLatch end = new CountDownLatch(2);
Runnable r1 = new Runnable() {
@Override
public void run() {
try {
start.countDown();
start.await();
System.out.println("In 1");
end.countDown();
end.await();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt(); //restore interruption status
}
}
};
Runnable r2 = new Runnable() {
@Override
public void run() {
try {
start.countDown();
start.await();
System.out.println("In 2");
end.countDown();
end.await();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt(); //restore interruption status
}
}
};
Upvotes: 6