Home > Java > javaTutorial > What are the ways to determine whether a thread has ended in Java?

What are the ways to determine whether a thread has ended in Java?

WBOY
Release: 2023-04-17 21:07:01
forward
2584 people have browsed it

方法1

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

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

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

方法2

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

方法3

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

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);  
        }  
    }  
}
Copy after login

判断线程池中的线程是否全部执行完毕的另外一种解决方案则是使用闭锁(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();
    }
}
Copy after login

The above is the detailed content of What are the ways to determine whether a thread has ended in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template