Merge pull request #5428 from vaibs28/master

BAEL-2188 Print even and odd numbers using 2 threads
This commit is contained in:
Tom Hombergs 2018-11-03 21:51:29 +01:00 committed by GitHub
commit 6bc487bfab
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 155 additions and 0 deletions

View File

@ -0,0 +1,72 @@
package com.baeldung.concurrent.evenandodd;
public class PrintEvenOdd {
public static void main(String... args) {
Printer print = new Printer();
Thread t1 = new Thread(new TaskEvenOdd(print, 10, false));
t1.setName("Odd");
Thread t2 = new Thread(new TaskEvenOdd(print, 10, true));
t2.setName("Even");
t1.start();
t2.start();
}
}
class TaskEvenOdd implements Runnable {
private int max;
private Printer print;
private boolean isEvenNumber;
TaskEvenOdd(Printer print, int max, boolean isEvenNumber) {
this.print = print;
this.max = max;
this.isEvenNumber = isEvenNumber;
}
@Override
public void run() {
int number = isEvenNumber == true ? 2 : 1;
while (number <= max) {
if (isEvenNumber) {
print.printEven(number);
} else {
print.printOdd(number);
}
number += 2;
}
}
}
class Printer {
boolean isOdd = false;
synchronized void printEven(int number) {
while (isOdd == false) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread()
.getName() + ":" + number);
isOdd = false;
notify();
}
synchronized void printOdd(int number) {
while (isOdd == true) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread()
.getName() + ":" + number);
isOdd = true;
notify();
}
}

View File

@ -0,0 +1,83 @@
package com.baeldung.concurrent.evenandodd;
import java.util.concurrent.Semaphore;
public class SemaphoreDemo {
public static void main(String[] args) {
SharedPrinter sp = new SharedPrinter();
Thread odd = new Thread(new Odd(sp, 10));
odd.setName("Odd");
Thread even = new Thread(new Even(sp, 10));
even.setName("Even");
odd.start();
even.start();
}
}
class SharedPrinter {
Semaphore semEven = new Semaphore(0);
Semaphore semOdd = new Semaphore(1);
public void printEvenNum(int num) {
try {
semEven.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread()
.getName() + ":"+num);
semOdd.release();
}
public void printOddNum(int num) {
try {
semOdd.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread()
.getName() + ":"+ num);
semEven.release();
}
}
class Even implements Runnable {
SharedPrinter sp;
int max;
Even(SharedPrinter sp, int max) {
this.sp = sp;
this.max = max;
}
@Override
public void run() {
for (int i = 2; i <= max; i = i + 2) {
sp.printEvenNum(i);
}
}
}
class Odd implements Runnable {
SharedPrinter sp;
int max;
Odd(SharedPrinter sp, int max) {
this.sp = sp;
this.max = max;
}
@Override
public void run() {
for (int i = 1; i <= max; i = i + 2) {
sp.printOddNum(i);
}
}
}