Is there any way to distinguish the main Thread fr

2020-03-03 07:41发布

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?

3条回答
贼婆χ
2楼-- · 2020-03-03 08:12

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();
    }
}    
查看更多
▲ chillily
3楼-- · 2020-03-03 08:14

From your question and your responses to comments I would suggest the following 2 approaches:

  1. Place all requests to an event queue and main thread will take the requests from request queue to call the method you are talking about. In this case there must be a contract that any other method wanting to access the method you are talking about can do it only via the event queue (same idea as EDT).

  2. Place an extra parameter in the method that you want to be called by main only to act as a token.Inside the method check if the token is correct (only main will have it/know it).If it is correct then proceed.Otherwise return false. Of course if you are allowed to make such a modification

查看更多
欢心
4楼-- · 2020-03-03 08:15

One possibility is to call Thread.currentThread() at the start of main(), and hold on to the reference.

查看更多
登录 后发表回答