Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a thread is already started or not in Java? [duplicate]

I am having a class which extends Thread.

I will start the thread at some point.

After some time I need to check if that thread is already started or not?

So that I can start the thread at that particular point.

My thread class will be,

public class BasicChatListener extends Thread{

    public void run(){


    }

}

I need the know the particular thread of a BasicChatListener class is running or not ? Because I have multiple threads are already running in my application.

How our stack members will help me.

like image 847
Human Being Avatar asked Jul 02 '13 09:07

Human Being


People also ask

How do you check if a thread is already running?

A thread is alive or running if it has been started and has not yet died. To check whether a thread is alive use the isAlive() method of Thread class. It will return true if this thread is alive, otherwise return false .

Can we start 2 thread twice?

No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception.

How can you know when another thread has finished its execution?

Check Thread. isAlive() in a polling fashion -- generally discouraged -- to wait until each Thread has completed, or. Unorthodox, for each Thread in question, call setUncaughtExceptionHandler to call a method in your object, and program each Thread to throw an uncaught Exception when it completes, or.

Can two threads run at the same time in Java?

Overview. Multi-thread programming allows us to run threads concurrently, and each thread can handle different tasks. Thus, it makes optimal use of the resources, particularly when our computer has a multiple multi-core CPU or multiple CPUs.


2 Answers

You can use Thread.getState() and use the corresponding states.

Note that by the time you read this state it may have changed, but you may be able to determine something of interest. Check out this state diagram for the available transitions.

like image 67
Brian Agnew Avatar answered Sep 24 '22 17:09

Brian Agnew


Use either Thread#isAlive()

if (Thread.currentThread().isAlive())

JavaDoc says:

Tests if this thread is alive. A thread is alive if it has been started and has not yet died.

Or, use Thread#getState() as

Thread.State currState = Thread.currentThread().getState();
if (currState != Thread.State.NEW && currState != Thread.State.TERMINATED)

JavaDoc says:

Returns the state of this thread. This method is designed for use in monitoring of the system state, not for synchronization control.

like image 22
Ravi K Thapliyal Avatar answered Sep 25 '22 17:09

Ravi K Thapliyal