有什么方法可以将主线程与它产生的任何线程区分开来吗? [英] Is there any way to distinguish the main Thread from any Threads that it spawns?

查看:64
本文介绍了有什么方法可以将主线程与它产生的任何线程区分开来吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道主线程上的getName()函数将返回字符串main,但这可以通过setName()进行更改.

I know that the getName() function on the main thread will return the String main, but this can be changed with setName().

有什么办法可以始终确定应用程序的主线程吗?

Is there any way to always determine the main thread of an application?

推荐答案

似乎主线程的 id 1,如

It seems that the main thread has an id of 1 as indicated by Thread.getId():

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

    public static void main(String[]args){
        System.out.println(isMainThread());
        new Thread( new Runnable(){
            public void run(){
                System.out.println(isMainThread());
            }
        }).start();
    }
}    

我不确定它是规范的一部分还是特定于实现的功能.

I'm not sure if it is part of the specification or an implementation-specific feature.

一种更可移植的方式是这样:

A more portable way is this:

class test{

    static long mainThreadId = Thread.currentThread().getId();

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

    public static void main(String[]args){
        System.out.println(isMainThread());
        new Thread( new Runnable(){
            public void run(){
                System.out.println(isMainThread());
            }
        }).start();
    }
}    

请注意,

必须位于主线程加载的类中(例如,包含main方法的类).例如,这不起作用:

with the caveat that mainThreadId has to be either in a class that is loaded by the main thread (e.g. the class containing the main method). For instance, this doesn't work:

class AnotherClass{
    static long mainThreadId = Thread.currentThread().getId();

    public static boolean isMainThread(){
        return Thread.currentThread().getId() == mainThreadId;
    }
}
class test{
    public static void main(String[]args){
        //System.out.println(isMainThread());
        new Thread( new Runnable(){
            public void run(){
                System.out.println(AnotherClass.isMainThread());
            }
        }).start();
    }
}    

这篇关于有什么方法可以将主线程与它产生的任何线程区分开来吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆