0% found this document useful (0 votes)
67 views

Program 27

The document describes a program that creates two threads - one that prints "Thread1" every 2 seconds and one that prints "Thread2" every 4 seconds. It does this by extending the Thread class to create two instances that override the run method - one prints "Thread1" and sleeps for 2 seconds in a for loop 5 times, the other prints "Thread2" and sleeps for 4 seconds in a for loop 5 times. The main method then starts both threads to run concurrently.

Uploaded by

Rushi Pandav
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

Program 27

The document describes a program that creates two threads - one that prints "Thread1" every 2 seconds and one that prints "Thread2" every 4 seconds. It does this by extending the Thread class to create two instances that override the run method - one prints "Thread1" and sleeps for 2 seconds in a for loop 5 times, the other prints "Thread2" and sleeps for 4 seconds in a for loop 5 times. The main method then starts both threads to run concurrently.

Uploaded by

Rushi Pandav
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Practical -27

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.

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
Thread2
Thread1
Thread1
Thread2
Thread1
Thread2
Thread2

You might also like