如何确定线程是否是Java中的主线程?

时间:2019-04-07 12:30:17

标签: java multithreading

在Java中,程序员可以更改主线程的名称。那么如何确定一个线程是否为主线程呢?

package bj.thread;

public class ThreadApp2 {

    public static void main(String[] args) {
        System.out.printf("The main thread name is %s\n", Thread.currentThread().getName());
        Thread.currentThread().setName("not-main");
        System.out.printf("The main thread name is %s\n", Thread.currentThread().getName());
    }
}

输出:

The main thread name is main
The main thread name is not-main

2 个答案:

答案 0 :(得分:1)

public static boolean isMainThread(){
    return Thread.currentThread().getId() == 1;
}

免责声明:文档中没有说明id == 1 =>它是主线程

答案 1 :(得分:0)

更常见的决定是,以main()方法启动程序后立即保存线程ID,并在需要时将其与其他线程ID进行比较

P.S如果您足够精通,可以使用特殊的Java Reflection API并将检查代码插入main()函数中,以开始任何代码。当您尝试使用第三方代码时,它会很有用。