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. String name;
  7.  // name of thread Thread t;
  8.  NewThread(String threadname)
  9.  { 
  10. name = threadname;

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