Write a Program to print numbers from 1-10 using multiple threads
Write a Program to print numbers from 1-10 using multiple threads
by |
25-Mar-2020
Tags:
Program
public class MultipleThreadingOddEven {
int count = 1;
int MAX = 10;
public void printOdd() {
synchronized (this) {
while (count < MAX) {
while (count % 2 == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(count + " ");
count++;
notify();
}
}
}
public void printEven() {
synchronized (this) {
while (count < MAX) {
while (count % 2 == 1) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(count + " ");
count++;
notify();
}
}
}
public static void main(String[] args) {
MultipleThreadingOddEven mt = new MultipleThreadingOddEven();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
mt.printEven();
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
mt.printOdd();
}
});
t1.start();
t2.start();
}
}
Output
1 2 3 4 5 6 7 8 9 10
Comments:
There are no comments.