Java check main thread

How to check if Java main thread is alive

To check if the main thread is running you cannot make use of the Thread.isAlive() method : you may get the error «Cannot make a static reference to the non-static method isAlive() from the type Thread«, as main is a static method thus can only access static methods.

To check if the main method thread is alive you can get the instance of the main thread by Thread.currentThread() static method.

  • Spring Boot + Redis Cloud Configuration and Setup Tutorial
  • Implementing Bubble Sort Algorithm using Java Program
  • Generate Maven Project Dependency Tree using MVN Command
  • Convert Collection List to Set using Java 8 Stream API
  • Java: RabbitMq Create a Queue Example
  • List of Java JDK Major Minor Version Numbers
  • 9 Ways to Loop Java Map (HashMap) with Code Examples
  • [fix] Java Spring Boot JPA SQLSyntaxErrorException: Encountered user at line 1 column 14
  • Project JDK is not defined [IntelliJ IDEA]
  • Deep Dive: Java Object Class from java.lang Package
  • Check if a Java Date String is Valid or Not (Java 8)
  • JdbcTemplate Batch Insert Example using Spring Boot
  • Convert JSON to Gson with type as ArrayList
  • [Fix] Java — Exception in thread main java.lang.IllegalThreadStateException
  • [Fix] Spring Boot: java.sql.SQLSyntaxErrorException: Unknown database
  • 7 deadly java.lang.OutOfMemoryError in Java Programming
  • List of jar files for Jax-ws (SOAP) based Java Web Services
  • Java get day of the week as an int using DayOfWeek
  • Add two numbers using Java Generics
  • Java Program to generate random string
  • Spring 5 IoC Example with application Context XML (ClassPathXmlApplicationContext) and Gradle.
  • [Java] How to throws Exception using Functional Interface and Lambda code
  • Error: Unable to access jarfile jarFileName.jar file [Windows]
  • Unhandled exception type InterruptedException : Java Threads
  • Fix: SyntaxError: ( was never closed [Python]
Читайте также:  Java post response json

Know the Author: With a Masters Degree in Computer Science, Rakesh is a highly experienced professional in the field. With over 18 years of practical expertise, he specializes in programming languages such as Java, Python, Sharepoint, PHP, and Rust. He is dedicated to delivering high-quality solutions and providing valuable insights to meet the unique challenges of the digital landscape. rakesh@code2care.org is where you can reach him out.

We keep our articles short so the focus remains on providing effective tech solutions while promoting healthier screen habits and enhancing overall well-being. 📝 💡 🌱 By reducing screen time, we contribute to a greener future, reducing carbon emissions and fostering digital well-being. 🌍 🌿 🔋

We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity — #BlackLivesMatters

Источник

[java] How to check if current thread is not main thread

I need to check if the thread running a certain piece of code is the main (UI) thread or not. How can I achieve this?

The answer is

Looper.myLooper() == Looper.getMainLooper() 

if this returns true, then you’re on the UI thread!

you can use below code to know if current thread is UI/Main thread or not

if(Looper.myLooper() == Looper.getMainLooper()) < // Current Thread is Main Thread. >
if(Looper.getMainLooper().getThread() == Thread.currentThread()) < // Current Thread is Main Thread. >

The best way is the clearest, most robust way: *

Thread.currentThread().equals( Looper.getMainLooper().getThread() ) 

Or, if the runtime platform is API level 23 (Marshmallow 6.0) or higher:

Looper.getMainLooper().isCurrentThread() 

See the Looper API. Note that calling Looper.getMainLooper() involves synchronization (see the source). You might want to avoid the overhead by storing the return value and reusing it.

Summarizing the solutions, I think that’s the best one:

boolean isUiThread = VERSION.SDK_INT >= VERSION_CODES.M ? Looper.getMainLooper().isCurrentThread() : Thread.currentThread() == Looper.getMainLooper().getThread(); 

And, if you wish to run something on the UI thread, you can use this:

new Handler(Looper.getMainLooper()).post(new Runnable() < @Override public void run() < //this runs on the UI thread >>); 

You can check

if(Looper.myLooper() == Looper.getMainLooper()) < // You are on mainThread >else < // you are on non-ui thread >

Allow me to preface this with: I acknowledged this post has the ‘Android’ tag, however, my search had nothing to do with ‘Android’ and this was my top result. To that end, for the non-Android SO Java users landing here, don’t forget about:

public static void main(String[] args < Thread.currentThread().setName("SomeNameIChoose"); /*. the rest of main. */ >

After setting this, elsewhere in your code, you can easily check if you’re about to execute on the main thread with:

if(Thread.currentThread().getName().equals("SomeNameIChoose")) < //do something on main thread >

A bit embarrassed I had searched before remembering this, but hopefully it will help someone else!

you can verify it in android ddms logcat where process id will be same but thread id will be different.

public bool IsMainThread => Build.VERSION.SdkInt >= BuildVersionCodes.M ? Looper.MainLooper.IsCurrentThread : Looper.MyLooper() == Looper.MainLooper; 

A simple Toast message works also as a quick check.

You can try Thread.currentThread().isDaemon()

Источник

How to check if current thread is not main thread

I need to check if the thread running a certain piece of code is the main (UI) thread or not. How can I achieve this?

example to demonstrate with thread example code2concept.blogspot.in/2015/02/… – nitesh Jun 29 ’15 at 18:12

9 Answers 9

Looper.myLooper() == Looper.getMainLooper() 

if this returns true, then you’re on the UI thread!

you can use below code to know if current thread is UI/Main thread or not

if(Looper.myLooper() == Looper.getMainLooper()) < // Current Thread is Main Thread. >
if(Looper.getMainLooper().getThread() == Thread.currentThread()) < // Current Thread is Main Thread. >

Should one consider the latter as the safer option as there is no guarantee that any arbitrary thread is associated with a Looper (assuming that the main thread is always associated with a looper)? – Janus Varmarken Jan 7 ’16 at 16:58

Looper.myLooper() will return null if the thread is not associated with a Looper. So both are safe and have the same result but the first one is a little bit slower while it searches inside a map to find out the looper and its associated thread and do some other stuff . – Saeed Masoumi Nov 3 ’18 at 8:26

The best way is the clearest, most robust way: *

Thread.currentThread().equals( Looper.getMainLooper().getThread() ) 

Or, if the runtime platform is API level 23 (Marshmallow 6.0) or higher:

Looper.getMainLooper().isCurrentThread() 

See the Looper API. Note that calling Looper.getMainLooper() involves synchronization (see the source). You might want to avoid the overhead by storing the return value and reusing it.

What do you mean by «under API 23 or higher»? That doesn’t make much sense to me..Also the exact same answer was posted by AAnkit, below.. – Mike Dec 2 ’15 at 20:44

@Mike Thanks, I fixed the API bit. AAnkit actually favours Looper.myLooper() == Looper.getMainLooper() , which I think is less clear. I credit greg7gkb. – Michael Allan Dec 2 ’15 at 21:00

should this be a comparison with == or equals() as Android Studio is raising a warning ? – 2cupsOfTech Jul 28 ’17 at 14:19

@2cupsOfTech On 2nd thought, that’s good advice. Currently both tests are the same at runtime because Thread does not override equals , and so falls back to == , but that could change in future. So I corrected the answer. – Michael Allan Oct 9 ’18 at 1:10

Summarizing the solutions, I think that’s the best one:

boolean isUiThread = VERSION.SDK_INT >= VERSION_CODES.M ? Looper.getMainLooper().isCurrentThread() : Thread.currentThread() == Looper.getMainLooper().getThread(); 

And, if you wish to run something on the UI thread, you can use this:

new Handler(Looper.getMainLooper()).post(new Runnable() < @Override public void run() < //this runs on the UI thread >>); 

You can check

if(Looper.myLooper() == Looper.getMainLooper()) < // You are on mainThread >else < // you are on non-ui thread >

Allow me to preface this with: I acknowledged this post has the ‘Android’ tag, however, my search had nothing to do with ‘Android’ and this was my top result. To that end, for the non-Android SO Java users landing here, don’t forget about:

public static void main(String[] args < Thread.currentThread().setName("SomeNameIChoose"); /*. the rest of main. */ >

After setting this, elsewhere in your code, you can easily check if you’re about to execute on the main thread with:

if(Thread.currentThread().getName().equals("SomeNameIChoose")) < //do something on main thread >

A bit embarrassed I had searched before remembering this, but hopefully it will help someone else!

Источник

How to check if current thread is not main thread

I need to check if the thread running a certain piece of code is the main (UI) thread or not. How can I achieve this?

example to demonstrate with thread example code2concept.blogspot.in/2015/02/… – nitesh Jun 29 ’15 at 18:12

10 Answers 10

Looper.myLooper() == Looper.getMainLooper() 

if this returns true, then you’re on the UI thread!

you can use below code to know if current thread is UI/Main thread or not

if(Looper.myLooper() == Looper.getMainLooper()) < // Current Thread is Main Thread. >
if(Looper.getMainLooper().getThread() == Thread.currentThread()) < // Current Thread is Main Thread. >

Should one consider the latter as the safer option as there is no guarantee that any arbitrary thread is associated with a Looper (assuming that the main thread is always associated with a looper)? – Janus Varmarken Jan 7 ’16 at 16:58

Looper.myLooper() will return null if the thread is not associated with a Looper. So both are safe and have the same result but the first one is a little bit slower while it searches inside a map to find out the looper and its associated thread and do some other stuff . – Saeed Masoumi Nov 3 ’18 at 8:26

The best way is the clearest, most robust way: *

Thread.currentThread().equals( Looper.getMainLooper().getThread() ) 

Or, if the runtime platform is API level 23 (Marshmallow 6.0) or higher:

Looper.getMainLooper().isCurrentThread() 

See the Looper API. Note that calling Looper.getMainLooper() involves synchronization (see the source). You might want to avoid the overhead by storing the return value and reusing it.

What do you mean by «under API 23 or higher»? That doesn’t make much sense to me..Also the exact same answer was posted by AAnkit, below.. – Mike Dec 2 ’15 at 20:44

@Mike Thanks, I fixed the API bit. AAnkit actually favours Looper.myLooper() == Looper.getMainLooper() , which I think is less clear. I credit greg7gkb. – Michael Allan Dec 2 ’15 at 21:00

should this be a comparison with == or equals() as Android Studio is raising a warning ? – 2cupsOfTech Jul 28 ’17 at 14:19

@2cupsOfTech On 2nd thought, that’s good advice. Currently both tests are the same at runtime because Thread does not override equals , and so falls back to == , but that could change in future. So I corrected the answer. – Michael Allan Oct 9 ’18 at 1:10

Summarizing the solutions, I think that’s the best one:

boolean isUiThread = VERSION.SDK_INT >= VERSION_CODES.M ? Looper.getMainLooper().isCurrentThread() : Thread.currentThread() == Looper.getMainLooper().getThread(); 

And, if you wish to run something on the UI thread, you can use this:

new Handler(Looper.getMainLooper()).post(new Runnable() < @Override public void run() < //this runs on the UI thread >>); 

You can check

if(Looper.myLooper() == Looper.getMainLooper()) < // You are on mainThread >else < // you are on non-ui thread >

Allow me to preface this with: I acknowledged this post has the ‘Android’ tag, however, my search had nothing to do with ‘Android’ and this was my top result. To that end, for the non-Android SO Java users landing here, don’t forget about:

public static void main(String[] args < Thread.currentThread().setName("SomeNameIChoose"); /*. the rest of main. */ >

After setting this, elsewhere in your code, you can easily check if you’re about to execute on the main thread with:

if(Thread.currentThread().getName().equals("SomeNameIChoose")) < //do something on main thread >

A bit embarrassed I had searched before remembering this, but hopefully it will help someone else!

Источник

Оцените статью