Home Tutorial Java Core Java Thread : getState() Example

 
 

Java Thread : getState() Example
Posted on: October 26, 2012 at 12:00 AM
Advertisement
This section explains how to get state of a thread in java Thread.

Java Thread : getState() Example

This section explains how to get state of a thread  in java Thread.

Thread  getState() :

Suppose you want to know the state of the thread so for that Java Thread provides Thread.getState() method to get the state of the thread.

public Thread.State getState() : This method returns the state of the specified thread. its function to monitor the
system state but do not for synchronization control.

Example :  This example display the different states of the thread.

class ThreadGetState implements Runnable {
	Thread thread;

	@Override
	public void run() {
		Thread.State state = thread.currentThread().getState();
		System.out.println(thread.currentThread().getName() + " state is - "
				+ state);

	}

	public static void main(String[] args) {
		Thread th = new Thread(new ThreadGetState());
		Thread th1 = new Thread(new ThreadGetState());
		th.start();
		try {
			th.sleep(1000);
		} catch (Exception e) {
			System.out.println(e);
		}
		Thread.State state = th.getState();
		System.out.println(th.getName() + " state is - " + state);
		System.out.println(th1.getName() + " state is - " + th1.getState());
		th1.start();
		try {
			th1.join();
		} catch (Exception e) {
			System.out.println(e);
		}
		System.out.println(th1.getName() + " state is - " + th1.getState());
	}

}

Output :

Thread-0 state is - RUNNABLE
Thread-0 state is - TERMINATED
Thread-1 state is - NEW
Thread-1 state is - RUNNABLE
Thread-1 state is - TERMINATED
Advertisement

Related Tags for Java Thread : getState() Example:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 26, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com