首页 > 解决方案 > How to determine if a thread is main thread in Java?

问题描述

In Java, programmers can change the name of main thread. So how to determine if a thread is main thread?

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 output:

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

标签: javamultithreading

解决方案


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

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


推荐阅读