Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class EvenOddPrinter {
- private volatile boolean odd = false;
- private int count = 1;
- private int MAX = 20;
- public void printOdd() {
- synchronized (this) {
- while (!odd) {
- try {
- wait();
- } catch (InterruptedException ie) {
- ie.printStackTrace();
- }
- System.out.println("Odd Thread :" + count);
- count++;
- if (count == MAX) return;
- odd = false;
- notify();
- }
- }
- }
- public void printEven() {
- synchronized (this) {
- while (odd) {
- try {
- wait();
- } catch (InterruptedException ie) {
- ie.printStackTrace();
- }
- System.out.println("Even Thread :" + count);
- count++;
- if (count == MAX) return;
- odd = true;
- notify();
- }
- }
- }
- }
- public class PrintThread implements Runnable {
- private EvenOddPrinter printer;
- private String evenOddString;
- public PrintThread(EvenOddPrinter printer, String evenOddString) {
- this.printer = printer;
- this.evenOddString = evenOddString;
- }
- @Override
- public void run() {
- if (evenOddString.equalsIgnoreCase("odd")) printer.printOdd();
- else printer.printEven();
- }
- }
- public class TesPrintEvenOdd {
- public static void main(String[] args) {
- EvenOddPrinter printer = new EvenOddPrinter();
- Thread th1 = new Thread(new PrintThread(printer, "Odd"));
- Thread th2 = new Thread(new PrintThread(printer, "Even"));
- th1.start();
- th2.start();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement