0% found this document useful (0 votes)
12 views2 pages

Code

The document provides a Java program that creates two threads: an 'Even' thread and an 'Odd' thread. The 'Even' thread prints even numbers every two seconds, while the 'Odd' thread prints odd numbers every five seconds. The program utilizes the Runnable interface to define the behavior of each thread and manages their execution through the main method.

Uploaded by

shreycoder1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views2 pages

Code

The document provides a Java program that creates two threads: an 'Even' thread and an 'Odd' thread. The 'Even' thread prints even numbers every two seconds, while the 'Odd' thread prints odd numbers every five seconds. The program utilizes the Runnable interface to define the behavior of each thread and manages their execution through the main method.

Uploaded by

shreycoder1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

(b) Write a program in java which creates two threads, “Even” thread and “Odd” thread and

print the even no using Even Thread after every two seconds and odd no using Odd Thread
after every five second.

Code:
package Unit_2;
class EvenRunnable implements Runnable {
@Override
public void run() {
int evenNumber = 0;
try {
while (true) {
System.out.println(Thread.currentThread().getName() + ": " + evenNumber);
evenNumber += 2;
Thread.sleep(2000); // Sleep for 2 seconds
}
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " interrupted");
}
}
}

class OddRunnable implements Runnable {


@Override
public void run() {
int oddNumber = 1;
try {
while (true) {
System.out.println(Thread.currentThread().getName() + ": " + oddNumber);
oddNumber += 2;
Thread.sleep(5000); // Sleep for 5 seconds
}
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " interrupted");
}
}
}

public class EvenOddThreads {


public static void main(String[] args) {
Thread evenThread = new Thread(new EvenRunnable(), "Even Thread");
Thread oddThread = new Thread(new OddRunnable(), "Odd Thread");

evenThread.start();
oddThread.start();
}
}
Output:

You might also like