- 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)
- Program :
- // Using Thread class
- class One extends Thread
- {
- public void run()
- {
- for ( ; ; )
- {
- try
- {
- sleep(1000);
- }
- catch(InterruptedException e)
- {
- }
- System.out.println("Good Morning");
- }
- }
- }
- class Two extends Thread { public void run() {
- for ( ; ; )
- {
- try
- {
- sleep(2000);
- }
- catch(InterruptedException e)
- {
- }
- System.out.println("Hello");
- }
- }
- }
- class Three extends Thread
- {
- public void run()
- {
- for ( ; ; )
- {
- try{
- sleep(3000);
- }
- catch(InterruptedException e)
- {
- }
- System.out.println("Welcome");
- }
- }
- }
- class MyThread { public static void main(String args[ ]) { Page 111
- Thread t = new Thread();
- One obj1=new One();
- Two obj2=new Two();
- Three obj3=new Three();
- Thread t1=new Thread(obj1);
- Thread t2=new Thread(obj2);
- Thread t3=new Thread(obj3);
- 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){}
- }
- }
- // Using Runnable interface class One implements Runnable {
- One( ) { new Thread(this, "One").start(); try{ Thread.sleep(1000); }catch(InterruptedException e){} }
- public void run() { for ( ; ; ) { try{ Thread.sleep(1000); }catch(InterruptedException e){} System.out.println("Good Morning"); } } }
- class Two implements Runnable {
- Two( ) { new Thread(this, "Two").start(); try{ Thread.sleep(2000); }catch(InterruptedException e){} }
- public void run() for ( ; ; ) { try{
- {
- Thread.sleep(2000); }catch(InterruptedException e){} System.out.println("Hello"); } } }
- class Three implements Runnable {
- Three( ) {
- new Thread(this, "Three").start(); try{ Thread.sleep(3000); }catch(InterruptedException e){} }
- public void run() { for ( ; ; ) { try{ Thread.sleep(3000); }catch(InterruptedException e){} System.out.println("Welcome"); } } }
- class MyThread { public static void main(String args[ ]) { One obj1=new One(); Two obj2=new Two(); Three obj3=new Three(); }
- }