方法1
通过Thread类中的isAlive()方法判断线程是否处于活动状态。
线程启动后,只要没有运行完毕,都会返回true。
【注】如果只是要等其他线程运行结束之后再继续操作,可以执行t.join(),即:在t执行完毕前挂起。
方法2
通过Thread.activeCount()方法判断当前线程的线程组中活动线程的数目,为1时其他线程运行完毕。
方法3
通过java.util.concurrent.Executors中的方法创建一个线程池,用这个线程池来启动线程。启动所有要启动的线程后,执行线程池的shutdown()方法,即在所有线程执行完毕后关闭线程池。然后通过线程池的isTerminated()方法,判断线程池是否已经关闭。线程池成功关闭,就意味着所有线程已经运行完毕了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Test { public static void main(String args[]) throws InterruptedException { ExecutorService exe = Executors.newFixedThreadPool( 50 ); for ( int i = 1 ; i <= 5 ; i++) { exe.execute( new SubThread(i)); } exe.shutdown(); while ( true ) { if (exe.isTerminated()) { System.out.println( "结束了!" ); break ; } Thread.sleep( 200 ); } } } |
判断线程池中的线程是否全部执行完毕的另外一种解决方案则是使用闭锁(CountDownLatch)来实现,CountDownLatch是一种灵活的闭锁实现,它可以使一个或多个线程等待一组事件发生。闭锁状态包括一个计数器,该计数器被初始化为一个正数,表示需要等待的事件数量。countDown方法递减计数器,表示有一个事件已经发生了,而await方法等待计数器达到零,即表示需要等待的事情都已经发生。可以使用闭锁来这样设计程序达到目的:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
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(); } } |
到此这篇关于Java如何判断线程是否结束的三种方法的文章就介绍到这了,更多相关Java 判断线程结束内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/y_index/article/details/87916555