Friday, February 27, 2015

Threads

1. Thread is light weight process, independent, separate path of execution.
2. multithreading is different from multiprocessing.
3. Life cycle of thread and it is decided by JVM new,runnable,running,nonrunnable,terminated.
4. Thread can created by extending thread class or implementing runnable interface.
5. thread scheduler is a part of JVM which thread needs to be executed and depends on the preemptive and time slicing(which is the priority of the thread)
6. join is used to wait for the thread to die, in other words the thread is completed fully and then proceeds with the other thread.
7. if the method is synchronized then it locks and wait for the method to complete and then resumes.
8. wait, notify and notifyall wait method releases the lock, while notify wakesup the thread. notifyall wakes up all the thread
9. interrupt is interrupting from the sleep or wait.

thread1.java

package awesomeThreads;

public class thread1 extends Thread{
 
 
 public void run(){
  
  for(int i=0;i<3;i++){
   System.out.println("First Thread");
  }
  
  try {
   Thread.sleep(10000);
   System.out.println("First Thread in sleeping mode");
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

thread2.java

package awesomeThreads;

public class thread2 implements Runnable {

 @Override
 public void run() {
  // TODO Auto-generated method stub
  System.out.println("Seccond Thread");
  
  try {
   Thread.sleep(5000);
   System.out.println("second Thread in sleeping mode");
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 

}
thread3.java

package awesomeThreads;

public class thread3 extends Thread{
 public void run(){
  
  for(int i=0;i<3;i++){
   System.out.println("third Thread");
  }
  
  try {
   Thread.sleep(2000);
   System.out.println("Third Thread in sleeping mode");
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

mainclass.java

package awesomeThreads;

public class mainclass {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Thread t1=new thread1();
  Runnable r2=new thread2();
  Thread t3=new thread3();
  
  t1.start();
  new Thread(r2).start();
  t3.start();
 }
}

Output:
First Thread
First Thread
First Thread
Seccond Thread
third Thread
third Thread
third Thread
Third Thread in sleeping mode
second Thread in sleeping mode
First Thread in sleeping mode

>>>
------------------------------------------------------------------------------------------------------------