there are two method here that will produce even and odd numbers by making method synchronized and other one is by using inter Thread Communication using wait() and notify().
Method #1
class Display {
public synchronized void display(String name) {
if (name.equals("even"))
{
System.out.print("Even Numbers are::");
for (int i = 1; i <= 20; i++) {
if (i % 2 == 0)
System.out.print(i + " ");
}
System.out.println();
} else
{
System.out.print("Odd Numbers are::");
for (int i = 1; i <= 20; i++) {
if (i % 2 != 0)
System.out.print(i + " ");
}
System.out.println();
}
}
}
class EvenOddUsingTwoThread extends
Thread {
Display d;
String name;
EvenOddUsingTwoThread(Display
d, String name) {
this.d = d;
this.name = name;
}
public void
run() {
d.display(name);
}
public static void
main(String[] args) {
Display d1 = new Display();
EvenOddUsingTwoThread
t1 = new EvenOddUsingTwoThread(d1, "even");
EvenOddUsingTwoThread
t2 = new EvenOddUsingTwoThread(d1, "odd");
t1.start();
t2.start();
}
}
Output
Method #2
public class EvenOddUsingThread {
static volatile int counter
= 1;
static
Object object = new Object();//
Monitor
public static void
main(String[] args) {
Thread tEven = new Thread(new
EvenProducer(), "Even ");
Thread tOdd = new Thread(new
OddProducer(), "Odd ");
tEven.start();
tOdd.start();
}
static class
EvenProducer implements Runnable {
public void
run() {
synchronized
(object) {
while
(counter <= 20) {
if (counter
% 2 == 0) {
System.out.println(Thread.currentThread().getName()
+ " :: " + counter);
counter++;
object.notify();
}
else {
try {
object.wait();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
static class
OddProducer implements Runnable {
public void
run() {
synchronized
(object) {
while
(counter <= 20) {
if (counter
% 2 != 0) {
System.out.println(Thread.currentThread().getName()
+ " ::" + counter);
counter++;
object.notify();
}
else {
try {
object.wait();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
}
Output: