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){
source share