Yash Kumbhar
23104b0081
EXTC A
ASSIGNMENT 5
Write a simple Java program that prints numbers from 1 to 100 using two threads. The first
thread should print all the odd numbers, and the second thread should print all the even
numbers.
CODE:
class OddNumberPrinter extends Thread {
@Override
public void run() {
for (int i = 1; i <= 100; i += 2) {
System.out.println(i);
try {
// Sleep to simulate some delay
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
class EvenNumberPrinter extends Thread {
@Override
public void run() {
for (int i = 2; i <= 100; i += 2) {
System.out.println(i);
try {
// Sleep to simulate some delay
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
public class OddEvenPrinter {
public static void main(String[] args) {
Thread oddThread = new OddNumberPrinter();
Thread evenThread = new EvenNumberPrinter();
oddThread.start();
evenThread.start();
try {
oddThread.join();
evenThread.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}