在java中同步线程

the*_*tna 4 java multithreading synchronization

我正在实现Runnable多线程的java 接口.我有一些n 线程.每个线程都有自己的生命.我想等到所有线程的生命到期.让我们说以下是这种情况

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();
}
Run Code Online (Sandbox Code Playgroud)

我正在做以下同步它.我不知道它是否正确.请让我知道我该怎么办?如果我的线程程序工作正常,有没有办法检查?

          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();
                    }   
Run Code Online (Sandbox Code Playgroud)

ass*_*ias 8

您可以将Runnables添加到ExecutorService并调用shutdown/awaitTermination,它将在所有任务完成后返回.javadoc中有一些例子 - 总结一下,你会写一些像:

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
Run Code Online (Sandbox Code Playgroud)