Friday, 15 June 2012

(June 14' 2012 - June 15' 2012)

We discussed the concept of Threads these 2 days. Java uses threads to enable the entire environment to be asynchronous. This helps reduce inefficiency by preventing the waste of CPU cycles. Also threads exist in several states such as running, ready to run, suspended, resumed, blocked.

          Creating a Thread: This can be do.ne by instantiating an object of type Thread. For this we can,
i) Implement the Runnable interface ,or
ii) Extend the Thread class itself.

Example:

          public class Threads{
  public static void main(String[] args){
  Thread th = new Thread();
  System.out.println("Numbers are printing line by line after 2 seconds : ");
  try{
  for(int i = 1;i <= 5;i++)
    {
  System.out.println(i);
  th.sleep(2000);
  }
  }
  catch(InterruptedException e){
    System.out.println("Thread interrupted!");
  e.printStackTrace();
  }
  }
}


OUTPUT-

Numbers are printing line by line after 2 seconds :
1
2
3
4

5



   Similarly, our program can spawn as many threads as it needs.

No comments:

Post a Comment