6

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.

Human Being
  • 8,269
  • 28
  • 93
  • 136

6 Answers6

6

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.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
3

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.

Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89
1

You can check it with isAlive..

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

Anirudha
  • 32,393
  • 7
  • 68
  • 89
1

I use this code Thread.isAlive()

nano_nano
  • 12,351
  • 8
  • 55
  • 83
1

You can use GetState()

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

or boolean isAlive()

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

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

Thread.isAlive() can determine if a thread is running.

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

Thread#getState(); can return the exact state of a thread.

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

AllTooSir
  • 48,828
  • 16
  • 130
  • 164