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