Write a program that executes two threads. One thread displays “Thread1” every 2,000 milliseconds, and the other displays “Thread2” every 4,000 milliseconds. Create the threads by extending the Thread class.

 

AIM: Write a program that executes two threads. One thread displays “Thread1” every 2,000 milliseconds, and the other displays “Thread2” every 4,000 milliseconds. Create the threads by extending the Thread class.

CODE:

class MyThread1 extends Thread{

            public void run(){

                        for( ; ; ){

                                    System.out.println("\n"+this.getName()+"\n");

                                    try{

                                    sleep(2000);

                                    }

                                    catch(InterruptedException ep){

                                    }

                        }

            }         

}

class MyThread2 extends Thread{

            public void run(){

                        for( ; ; ){

                                    System.out.println("\n"+this.getName()+"\n");

                                    try{

                                    sleep(4000);

                                    }

                                    catch(Exception ep){

                                    }

                        }

            }         

}

class threadMain{

public static void main(String args[]){

            MyThread1 t1 = new MyThread1();

            t1.start();

            t1.setName("Thread1");

           

            MyThread2 t2 = new MyThread2();

            t2.start();

            t2.setName("Thread2");

}

}

 

OUTPUT:



It will be infinite loop to stop it we have to press CTRL+C.

Comments

Popular posts from this blog

Write an application that illustrates method overriding in the same package and different packages. Also demonstrate accessibility rules in inside and outside packages

Describe abstract class called Shape which has three subclasses say Triangle, Rectangle, and Circle. Define one method area()in the abstract class and override this area() in these three subclasses to calculate for specific object.

Write a program that illustrates interface inheritance. Interface P12 inherits from both P1 and P2. Each interface declares one constant and one method. The class Q implements P12. Instantiate Q and invoke each of its methods. Each method displays one of the constants.