Blogger Information
Blog 5
fans 0
comment 0
visits 9466
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Java如何判断线程是否结束的三种方法
P粉684418227
Original
5092 people have browsed it

目录
方法1
方法2
方法3

方法1
通过Thread类中的isAlive()方法判断线程是否处于活动状态。

线程启动后,只要没有运行完毕,都会返回true。

【注】如果只是要等其他线程运行结束之后再继续操作,可以执行t.join(),即:在t执行完毕前挂起。

方法2
通过Thread.activeCount()方法判断当前线程的线程组中活动线程的数目,为1时其他线程运行完毕。

Java技术迷

方法3
通过java.util.concurrent.Executors中的方法创建一个线程池,用这个线程池来启动线程。启动所有要启动的线程后,执行线程池的shutdown()方法,即在所有线程执行完毕后关闭线程池。然后通过线程池的isTerminated()方法,判断线程池是否已经关闭。线程池成功关闭,就意味着所有线程已经运行完毕了。
`import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {

  1. public static void main(String args[]) throws InterruptedException {
  2. ExecutorService exe = Executors.newFixedThreadPool(50);
  3. for (int i = 1; i <= 5; i++) {
  4. exe.execute(new SubThread(i));
  5. }
  6. exe.shutdown();
  7. while (true) {
  8. if (exe.isTerminated()) {
  9. System.out.println("结束了!");
  10. break;
  11. }
  12. Thread.sleep(200);
  13. }
  14. }

}判断线程池中的线程是否全部执行完毕的另外一种解决方案则是使用闭锁(CountDownLatch)来实现,CountDownLatch是一种灵活的闭锁实现,它可以使一个或多个线程等待一组事件发生。闭锁状态包括一个计数器,该计数器被初始化为一个正数,表示需要等待的事件数量。countDown方法递减计数器,表示有一个事件已经发生了,而await方法等待计数器达到零,即表示需要等待的事情都已经发生。可以使用闭锁来这样设计程序达到目的:public class CountDownLatchApproach {undefined
public static void main(String[] args) throws IOException, InterruptedException {undefined
final int nThreads = 10;
final CountDownLatch endGate = new CountDownLatch(nThreads);
final File stream = new File(“c:\temp\stonefeng\stream.txt”);
final OutputStream os = new FileOutputStream(stream);
final OutputStreamWriter writer = new OutputStreamWriter(os);
ExecutorService exec = Executors.newCachedThreadPool();
for (int i = 0; i < nThreads; i++) {undefined
final int num = i;
Runnable task = new Runnable() {undefined
@Override
public void run() {undefined
try {undefined
writer.write(String.valueOf(num)+”\n”);
} catch (IOException e) {undefined
e.printStackTrace();
} finally {undefined
endGate.countDown();
}
}
};
exec.submit(task);
}
endGate.await();
writer.write(“—-END—-\n”);
writer.close();
}
}`

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post