Is there a way to distinguish the main topic from any threads that it spawns?

I know that the getName() function in the main thread will return the main string, but it can be changed using setName() .

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

+4
source share
3 answers

It seems that the main thread has identifier 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 this is part of the specification or an implementation-specific function.

More portable way:

 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 must be either in a class that is loaded by the main thread (for example, a class containing the main method). For example, this does not 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(); } } 
+5
source

One possibility is to call Thread.currentThread() at the beginning of main() and hold the link.

+7
source

From your question and your answers to the comments, I would suggest the following two approaches:

  • Put all the requests in the event queue, and the main thread will be requests from the request queue to call the method you are talking about. In this case, there must be a contract that any other method wishing to access the method you are talking about can only do this through an event queue (the same idea as EDT).

  • Put an additional parameter in the method that you want to call the main one in order to act as a token. Inside the method, they check if the token is correct (only main will have / know it). If this is correct, then continue.Otherwise return false. Of course, if you are allowed to make such a modification

+2
source

Source: https://habr.com/ru/post/1393741/


All Articles