Write
a program that executes two threads. One thread will print the even numbers and
the another thread will print odd numbers from 1 to 50.
class NewThread extends Thread
{
NewThread(String threadname)
{
super(threadname);
}
public void run()
{
if( getName().equals("Odd")==true)
{
for(int i=1;i<=50;i=i+2)
{
System.out.print(" " + i);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Exception
Occurred.");
}
}
}
else
{
for(int i=2;i<=50;i=i+2)
{
System.out.print(" " + i);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Exception
Occurred.");
}
}
}
}
}
public class Example
{
public static void main(String[] args)
{
NewThread t1 = new
NewThread("Odd");
NewThread t2 = new
NewThread("Even");
t1.start();
t2.start();
}
OUTPUT:-
1 2 4 3 6 5 8 7 10 9 12 11 14 13 16 15
17 18 20 19 22 21 24 23 26 25 28 27 29 30 32 31 34 33 35 36 37 38 40 39 42 41
43 44 46 45 47 48 50 49
Comments
Post a Comment