Sunday 2 March 2014

Thread States

1. Once a thread starts executing it will be in one of below states
    a. Running
    b. Ready to Run (Waiting in the ready queue for their turn)
    c. sleeping
    d. waiting
    e blocked

2. Not all threads are interruptible, we can interrupt a thread which is sleeping or which is in waiting state. But if a thread block on I/O it will not respond to interrupts. When a thread is blocked waiting to get the lock required by a synchronized statement, it also will not respond to interrupt requests.

3. We can interrupt a thread that is sleeping 
class ThreadInterrupt implements Runnable{
 public void run(){
  System.out.println("Time to sleep");
  try{
   Thread.currentThread().sleep(1000);
  }
  catch(InterruptedException e){
   System.out.println(e);
  }
 }

 public static void main(String args[]){
  ThreadInterrupt task1 = new ThreadInterrupt();
  Thread t1 = new Thread(task1);
  t1.start();
  t1.interrupt();
 }
}
   
Output
Time to sleep
java.lang.InterruptedException: sleep interrupted

4. We can interrupt a thread that is waiting on particular object
class ThreadInterrupt implements Runnable{
 Object obj = new Object();

 public void run(){
  System.out.println("Time to sleep");
   synchronized(obj){
    try{
     obj.wait();
    }
    catch(InterruptedException e){
     System.out.println(e);
    }
   }
  }

  public static void main(String args[]){
   ThreadInterrupt task1 = new ThreadInterrupt();
   Thread t1 = new Thread(task1);
   t1.start();
   t1.interrupt();
  }
}
   
Output
Time to sleep
java.lang.InterruptedException

5. A Thread is not interruptible if it is waiting on I/O
import java.io.*;
class ThreadInterrupt implements Runnable{
 static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

 public void run(){
  try{
   System.out.println("Enter input");
   String s = br.readLine();
   System.out.println("You entered " +s);
  }
  catch(Exception e){
   System.out.println(e);
  }
 }

 public static void main(String args[]){
  ThreadInterrupt task1 = new ThreadInterrupt();
  Thread t1 = new Thread(task1);
  t1.start();
  t1.interrupt();
 }
}

Output
Enter input
PTR
You entered PTR
   
6. The difference between blocked and waiting state is, a thread which is in waiting state can be interruptible, where as, a thread which is blocked on acquiring lock or I/O is not interruptible


Notify Thread                                                 Thread states                                                 Home

No comments:

Post a Comment