Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

synchronizing thread in java

I am implementing java Runnable interface for multithreading. I have some n number of threads. Each of the thread has its own life. I would like to wait till life of all the threads get expire. Lets say following is the case

for(int i = 0; i< k;i++){
 Thread thread1 = new Thread(new xyz())
 Thread thread2 = new Thread(new abc())
 Thread thread3 = new Thread(new mno())
 thread1.start();
 thread2.start();
 thread3.start();
}

I am doing following to synchronize it. I don't know if it is correct. Please let me know how would I do it? And is there any way to check, if my threaded program is working correctly?

          if(thread2.isAlive())
                try {
                    thread2.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            if(thread1.isAlive())
                    try {
                        thread1.join();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
            if(thread3.isAlive())
                try {
                        thread3.join();
                } catch (InterruptedException e) {
                e.printStackTrace();
                    }   
like image 392
thetna Avatar asked Dec 05 '22 15:12

thetna


1 Answers

You could add your Runnables to an ExecutorService and call shutdown / awaitTermination which will return once all tasks have completed. There are a few examples in the javadoc - in summary you would write something like:

ExecutorService executor = Executors.newFixedThreadPool(3);

executor.submit(runnable1);
executor.submit(runnable2);
executor.submit(runnable3);

executor.shutdown();
boolean allRunnableAreDone = executor.awaitTermination(60, TimeUnit.SECONDS);

// This line is reached once all runnables have finished their job
// or the 60 second timeout has expired
like image 187
assylias Avatar answered Dec 15 '22 00:12

assylias