Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check which thread is executing code in Java?

I have a multi-threaded Java program with a bunch of rules around threading: For example, code in class A should only be called from the UI thread; 3 methods in class B must be called only from the network thread, etc.

Any suggestions on how to do assertions or other code checks that these rules are being followed? I'd like to do the equivalent of testing for "invariants" to prevent coding errors on thread usage.

like image 895
Nils Avatar asked Jan 13 '11 19:01

Nils


People also ask

Which method is used to check if a thread is running in Java?

The isAlive() method is used to check if a thread has finished executing. If the thread is still running, it returns true, otherwise false.

How are threads executed in Java?

start. Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).

How do I get current thread?

A thread can be created by implementing the Runnable interface and overriding the run() method. The current thread is the currently executing thread object in Java. The method currentThread() of the Thread class can be used to obtain the current thread.

What state is a thread in when it is executing?

A thread in the runnable state is executing in the Java virtual machine but it may be waiting for other resources from the operating system such as processor.


1 Answers

Thread.currentThread().getName()

like image 66
adamfisk Avatar answered Sep 17 '22 14:09

adamfisk