Consider using a countdown latch to maximize parallelism. Basically, you can create a singleton / static countdownLatch with a total of 1 and let multiple threads wait for the same countdown. check below what i did
The main thread that defines the start time of the stream.
package mylab.threads; import java.util.TimerTask; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class MainThread extends TimerTask { private static CountDownLatch countDown = new CountDownLatch(1); private ExecutorService es = Executors.newCachedThreadPool(); @Override public void run() { try { Thread1 thread1 = new Thread1(); thread1.setDoneSignal(countDown); es.submit(thread1); Thread2 thread2 = new Thread2(); thread2.setDoneSignal(countDown); es.submit(thread2); System.out.println("waiting main.. "); synchronized(this) { this.wait(2000); } System.out.println("kick off threads.."); countDown.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } }
Identify the threads you want to run in parallel
package mylab.threads; import java.util.Date; import java.util.TimerTask; import java.util.concurrent.CountDownLatch; public class Thread1 extends TimerTask{ private CountDownLatch doneSignal = null; public CountDownLatch getDoneSignal() { return doneSignal; } public void setDoneSignal(CountDownLatch doneSignal) { this.doneSignal = doneSignal; } @Override public void run() { try { this.doneSignal.await(); System.out.println("get going thread 1 -"+new Date().getTime()); synchronized(this) { this.wait(3000); } System.out.println("Exiting thread 1 - "+new Date().getTime()); } catch (InterruptedException e) {
Finally, start the main thread.
package mylab.threads; public class ThreadTest { public static void main(String[] args) { MainThread mt = new MainThread(); mt.run(); } }
Here is the conclusion
waiting main.. kick off threads.. get going thread 1 -1387513662107 get going thread 2 -1387513662107 Exiting thread 1 - 1387513665108 Exiting thread 2 - 1387513665108
source share