Java代码如何检测线程是否存活呢?
下文笔者讲述使用java代码检测线程是否存活的方法分享,如下所示
检测线程是否存活的示例
实现思路: 使用Thread类中的isAlive方法即可检测一个线程是否存活例:
检测线程是否存活的示例
public class TwoThreadAlive extends Thread { public void run() { for (int i = 0; i < 10; i++) { printMsg(); } } public void printMsg() { Thread t = Thread.currentThread(); //获取当前线程名称 String name = t.getName(); System.out.println("name=" + name); } public static void main(String[] args) { TwoThreadAlive tt = new TwoThreadAlive(); tt.setName("Thread"); System.out.println("before start(), tt.isAlive()=" + tt.isAlive()); tt.start(); System.out.println("just after start(), tt.isAlive()=" + tt.isAlive()); for (int i = 0; i < 10; i++) { tt.printMsg(); } System.out.println("The end of main(), tt.isAlive()=" + tt.isAlive()); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。