Monday, 13 July 2015

Java Programs[Important]

  1.   WRITE A JAVA PROGRAM that creates 3 threads by extending Thread class. First thread displays “Good Morning” every 1 sec, the second thread displays “Hello” every 2 seconds and the third displays “Welcome” every 3 seconds. (Repeat the same by implementing Runnable)
  2.  
  3. Program :
  4.  
  5. // Using Thread class 
  6. class One extends Thread 
  7. public void run()
  8.  { 
  9. for ( ; ; ) 
  10. try
  11. sleep(1000); 
  12. }
  13. catch(InterruptedException e)
  14. {
  15. }
  16.  System.out.println("Good Morning"); 
  17. }
  18.  } 
  19. }
  20.  
  21. class Two extends Thread { public void run()   
  22.  

  23.  
  24. for ( ; ; )
  25.  { 
  26. try
  27. sleep(2000); 
  28. }
  29. catch(InterruptedException e)
  30. {
  31. System.out.println("Hello");
  32.  } 
  33. }
  34.  
  35. class Three extends Thread 
  36. public void run() 
  37. for ( ; ; )
  38.  { 
  39. try{ 
  40. sleep(3000);
  41.  }
  42. catch(InterruptedException e)
  43. {
  44. System.out.println("Welcome");
  45.  }
  46.  }
  47.  }
  48.  
  49. class MyThread { public static void main(String args[ ]) {   Page 111
  50.  

  51.  
  52. Thread t = new Thread();
  53.  One obj1=new One(); 
  54. Two obj2=new Two(); 
  55. Three obj3=new Three(); 
  56. Thread t1=new Thread(obj1);
  57.  Thread t2=new Thread(obj2); 
  58. Thread t3=new Thread(obj3);
  59.  
  60. t1.start(); try{ t.sleep(1000); }catch(InterruptedException e){} t2.start(); try{ t.sleep(2000); }catch(InterruptedException e){} t3.start(); try{ t.sleep(3000); }catch(InterruptedException e){}
  61.  
  62. }   

  63. }
  64.  
  65. // Using Runnable interface class One implements Runnable {
  66.  
  67. One( ) { new Thread(this, "One").start(); try{ Thread.sleep(1000); }catch(InterruptedException e){} }
  68.  
  69. public void run() { for ( ; ; ) { try{ Thread.sleep(1000); }catch(InterruptedException e){} System.out.println("Good Morning"); } } }

  70. class Two implements Runnable {
  71.  
  72. Two( ) { new Thread(this, "Two").start(); try{ Thread.sleep(2000); }catch(InterruptedException e){} }
  73.  
  74. public void run() for ( ; ; ) { try{
  75.  
  76. {
  77.  
  78. Thread.sleep(2000); }catch(InterruptedException e){} System.out.println("Hello"); } } }
  79.  
  80. class Three implements Runnable {
  81.  
  82. Three( ) { 
  83.  

  84.  
  85. new Thread(this, "Three").start(); try{ Thread.sleep(3000); }catch(InterruptedException e){} }
  86.  
  87. public void run() { for ( ; ; ) { try{ Thread.sleep(3000); }catch(InterruptedException e){} System.out.println("Welcome"); } } }
  88.  
  89. class MyThread { public static void main(String args[ ]) { One obj1=new One(); Two obj2=new Two(); Three obj3=new Three(); }  

  90.  
  91. }