Monday, 13 July 2015

Java Programs[Important]

  1. WRITE A JAVA PROGRAM for creating multiple threads.
  2.  
  3. Program :
  4.  
  5. class NewThread implements Runnable 
  6. { 
  7. String name;
  8.  // name of thread Thread t;
  9.  NewThread(String threadname)
  10.  { 
  11. name = threadname;

  12. t = new Thread(this, name); 
  13. System.out.println("New thread: " + t);
  14.  t.start(); 
  15. // Start the thread 
  16. } // This is the entry point for thread.
  17.  public void run() 
  18. { 
  19. try 
  20. { 
  21. for(int i = 5; i > 0; i--) 
  22. { 
  23. System.out.println(name + ": " + i);
  24.  Thread.sleep(1000);
  25.  } 
  26. }
  27.  catch (InterruptedException e)
  28.  { 
  29. System.out.println(name + "Interrupted");
  30.  }
  31.  System.out.println(name + " exiting."); 
  32. }
  33.  }
  34.  class MultiThreadDemo 
  35. {
  36.  public static void main(String args[])
  37.  {
  38.  new NewThread("One"); // start threads new NewThread("Two"); new NewThread("Three");
  39.  try 
  40. { // wait for other threads to end Thread.sleep(10000);
  41.  } 
  42. catch (InterruptedException e)
  43.  {
  44.  System.out.println("Main thread Interrupted"); 
  45. } 
  46. System.out.println("Main thread exiting.");
  47.  } 
  48. }
  49.