4

我正在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();
}

我正在做以下同步它。我不知道这是否正确。请让我知道我该怎么做?有什么方法可以检查我的线程程序是否正常工作?

          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();
                    }   
4

5 回答 5

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
于 2012-06-28T15:48:06.333 回答
4

尽管ExecutorService@assylias 的回答很好,这里有更多关于join().

你不需要isAlive()在你之前测试join()Thread.join()代码已经这样做了。这是那里的代码片段:

while (isAlive()) {
    wait(0);
}

所以你需要做的就是加入你的线程:

   try {
       thread2.join();
       thread1.join();
       thread3.join();
   } catch (InterruptedException e) {
       // always a good pattern
       Thread.currentThread().interrupt();
       e.printStackTrace();
   }
于 2012-06-28T15:52:49.637 回答
2

作为一个简单的解决方案,您可以将所有线程放在一个列表中,然后在它们启动后调用它们:

List<Thread> threads = new ArrayList<>();
for(int i = 0; i< k;i++)
{
  //create threads
  Thread thread1 = new Thread(new xyz());
  Thread thread2 = new Thread(new abc());
  Thread thread3 = new Thread(new mno());

  //store threads
  threads.add(thread1);
  threads.add(thread2);
  threads.add(thread3);

  //start threads
  thread1.start();
  thread2.start();
  thread3.start();
}

//join all threads
for(Thread t : threads)
   t.join();

//You are here after all threads have terminated
于 2012-06-28T15:51:12.583 回答
1

join()方法不加入线程,而是加入锁定对象。等待线程必须调用lockObject.join(),工作线程必须lockObject.notify()在完成后调用。等待的线程将被通知并可以继续其工作。您还需要synchronize围绕这些调用设置块。

我也推荐像 assylias 提到的 Executor,它比你自己实现这个行为要容易得多。

于 2012-06-28T15:51:27.067 回答
1

Java 包含在java.util.concurrent 中执行此类操作的机制。

在您的情况下,您可能需要CountDownLatchExecutorService

于 2012-06-28T15:45:17.187 回答