Is there any way to distinguish the main Thread from any Threads that it spawns?

前端 未结 3 876
予麋鹿
予麋鹿 2021-01-05 23:09

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

Is

3条回答
  •  臣服心动
    2021-01-05 23:43

    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();
        }
    }    
    

    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();
        }
    }    
    

提交回复
热议问题