multithread.java
package multithread;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Multithread {
boolean odd;
int count = 1;
int s;
public void Multithread(int b)
{
s=b;
}
public void printOdd() {
synchronized (this) {
while (count < s) {
System.out.println("Checking odd loop");
while (!odd) {
try {
System.out.println("Odd waiting : " + count);
wait();
System.out.println("Notified odd :" + count);
} catch (InterruptedException e) {
}
}
System.out.println("Odd Thread :" + count);
count++;
odd = false;
notify();
}
}
}
public void printEven() {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
synchronized (this) {
while (count < s) {
System.out.println("Checking even loop");
while (odd) {
try {
System.out.println("Even waiting: " + count);
wait();
System.out.println("Notified even:" + count);
} catch (InterruptedException e) {
}
}
System.out.println("Even thread :" + count);
count++;
odd = true;
notify();
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader ( new InputStreamReader(System.in));
System.out.println("Enter the limit ");
int a=Integer.parseInt(br.readLine());
Multithread oep = new Multithread();
oep.Multithread(a);
oep.odd = true;
Thread t1 = new Thread(oep::printEven);
Thread t2 = new Thread(oep::printOdd);
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
}
}
}
OUTPUT:
No comments:
Post a Comment