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

EvenOddThread

Uploaded by

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

EvenOddThread

Uploaded by

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

class EvenOddPrinter {

private int limit;


private int number = 1;
private final Object lock = new Object();

public EvenOddPrinter(int limit) {


this.limit = limit;
}

public void printOdd() {


synchronized (lock) {
while (number <= limit) {
if (number % 2 == 0) {
try {
lock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} else {
System.out.println("Odd: " + number);
number++;
lock.notify();
}
}
}
}

public void printEven() {


synchronized (lock) {
while (number <= limit) {
if (number % 2 != 0) {
try {
lock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} else {
System.out.println("Even: " + number);
number++;
lock.notify();
}
}
}
}
}

public class EvenOddThread {


public static void main(String[] args) {
int limit = 10;
EvenOddPrinter printer = new EvenOddPrinter(limit);

Thread oddThread = new Thread(new Runnable() {


@Override
public void run() {
printer.printOdd();
}
});

Thread evenThread = new Thread(new Runnable() {


@Override
public void run() {
printer.printEven();
}
});

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

You might also like