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. { 
  8. public void run()
  9.  { 
  10. for ( ; ; ) 
  11. { 
  12. try
  13. { 
  14. sleep(1000); 
  15. }
  16. catch(InterruptedException e)
  17. {
  18. }
  19.  System.out.println("Good Morning"); 
  20. }
  21.  } 
  22. }
  23.  
  24. class Two extends Thread { public void run()   { 
  25.  

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

  60.  
  61. Thread t = new Thread();
  62.  One obj1=new One(); 
  63. Two obj2=new Two(); 
  64. Three obj3=new Three(); 
  65. Thread t1=new Thread(obj1);
  66.  Thread t2=new Thread(obj2); 
  67. Thread t3=new Thread(obj3);
  68.  
  69. 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){}
  70.  
  71. }   

  72. }
  73.  
  74. // Using Runnable interface class One implements Runnable {
  75.  
  76. One( ) { new Thread(this, "One").start(); try{ Thread.sleep(1000); }catch(InterruptedException e){} }
  77.  
  78. public void run() { for ( ; ; ) { try{ Thread.sleep(1000); }catch(InterruptedException e){} System.out.println("Good Morning"); } } }

  79. class Two implements Runnable {
  80.  
  81. Two( ) { new Thread(this, "Two").start(); try{ Thread.sleep(2000); }catch(InterruptedException e){} }
  82.  
  83. public void run() for ( ; ; ) { try{
  84.  
  85. {
  86.  
  87. Thread.sleep(2000); }catch(InterruptedException e){} System.out.println("Hello"); } } }
  88.  
  89. class Three implements Runnable {
  90.  
  91. Three( ) { 
  92.  

  93.  
  94. new Thread(this, "Three").start(); try{ Thread.sleep(3000); }catch(InterruptedException e){} }
  95.  
  96. public void run() { for ( ; ; ) { try{ Thread.sleep(3000); }catch(InterruptedException e){} System.out.println("Welcome"); } } }
  97.  
  98. class MyThread { public static void main(String args[ ]) { One obj1=new One(); Two obj2=new Two(); Three obj3=new Three(); }  

  99.  
  100. }