美文网首页
Java 查看线程是否存活

Java 查看线程是否存活

作者: 西贝巴巴 | 来源:发表于2021-03-25 10:05 被阅读0次
package com.company;

/*
继承 Thread 类并使用 isAlive() 方法来检测一个线程是否存活
*/
public class ThreadTest1 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);
    }

    public static void main(String[] args) {
        ThreadTest1 tt = new ThreadTest1();
        tt.setName("Thread");
        boolean isActivityStart = tt.isAlive();
        System.out.println("before start(), tt.isAlive()=" + isActivityStart);
        tt.start();
        boolean isActivityNow = tt.isAlive();
        System.out.println("just after start(), tt.isAlive()=" + isActivityNow);
        for (int i = 0; i < 10; i++) {
            tt.printMsg();
        }
        ThreadTest1 tt2 = new ThreadTest1();
        tt2.start();

        System.out.println("The end of main(), tt.isAlive()=" + tt.isAlive());

    }
}

相关文章

网友评论

      本文标题:Java 查看线程是否存活

      本文链接:https://www.haomeiwen.com/subject/inkcqltx.html