public class ThreadState{
public static void main(String[] args){
Thread one = new Thread(new Runnable(){
@Override
public void run(){
System.out.println(Thread.currentThread().getName() + " " + Thread.currentThread().getState());
}
});
Thread two = new Thread(new Runnable(){
@Override
public void run(){
System.out.println(Thread.currentThread().getName() + " " + Thread.currentThread().getState());
}
});
System.out.println(one.getState());
System.out.println(two.getState());
one.start();
two.start();
System.out.println(one.getState());
System.out.println(two.getState());
System.out.println(one.getState());
System.out.println(two.getState());
System.out.println("Main ");
}
}
I'm trying to learn Thread.State in java but I'm confusing between them. When I run the above code I got multiple results ( I know because of Multithreading ).
But I'm unable to understand state of them.
1) Here two outputs which I want to learn can you explain any one them?
NEW
NEW
RUNNABLE
RUNNABLE
RUNNABLE
RUNNABLE
Thread-0 RUNNABLE
Thread-1 RUNNABLE
Main
The second one is this.
NEW
NEW
RUNNABLE
BLOCKED
BLOCKED // 2) Why go to again BLOCKED state? as before it was in RUNNABLE state
BLOCKED
Main
Thread-0 RUNNABLE
Thread-1 RUNNABLE
I already know about what is the NEW state, What is the RUNNABLE state. But I'm confused about BLOCKED and WAITING state.
Student object1 = new Student(); // any shared resource
Thread t1 = new Thread(/*......*/); => NEW State
Thread t2 = new Thread(/*......*/); => NEW State
t1.start(); => RUNNABLE STATE
t2.start(); => RUNNABLE STATE
`t1` and `t2` trying to get lock on object1 and `t1` successfully got locked on object1.
3) Now t2
will be in BLOCKED State or WAITING State?
`t1` called `wait()` method and released lock.
`t2` got the lock and `t1` now in WAITING state.
`t2` called `notify();` and released lock.
`t1` got the lock
4) t2
will be in BLOCKED State or Waiting State?
`t1.run();` finished => TERMINATED State
`t2.run();` finished => TERMINATED State
5) JVM keep history of each thread even after thread's dead? If no then how JVM show TERMINATED state of thread that is already gone?