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.


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.

class NewThread extends Thread
{
NewThread(String threadname)
{
super(threadname);
}
public void run()
{
if( getName().equals("Thread1")==true)
{
for(int i=1;i<=5;i++)
{
System.out.println("Thread1");

try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
System.out.println("Exception Occurred.");
}
}
}
else

{
for(int i=1;i<=5;i++)
{
System.out.println("Thread2");

try
{
Thread.sleep(4000);
}
catch(InterruptedException e)
{
System.out.println("Exception Occurred.");
}
}
}
}
}
public class Example
{
public static void main(String[] args)
{
NewThread t1 = new NewThread("Thread1");
NewThread t2 = new NewThread("Thread2");
t1.start();
t2.start();
}
}
OUTPUT:-
Thread1
Thread2
Thread1
Thread1Thread2

Thread1
Thread2
Thread1
Thread2
Thread2

Comments