Printing Even and Odd using two Threads in Java

2019-01-04 10:21发布

I tried the code below. I took this piece of code from some other post which is correct as per the author. But when I try running, it doesn't give me the exact result.

This is mainly to print even and odd values in sequence.

public class PrintEvenOddTester {



    public static void main(String ... args){
        Printer print = new Printer(false);
        Thread t1 = new Thread(new TaskEvenOdd(print));
        Thread t2 = new Thread(new TaskEvenOdd(print));
        t1.start();
        t2.start();
    }


}



class TaskEvenOdd implements Runnable {

    int number=1;
    Printer print;

    TaskEvenOdd(Printer print){
        this.print = print;
    }

    @Override
    public void run() {

        System.out.println("Run method");
        while(number<10){

            if(number%2 == 0){
                System.out.println("Number is :"+ number);
                print.printEven(number);
                number+=2;
            }
            else {
                System.out.println("Number is :"+ number);
                print.printOdd(number);
                number+=2;
            }
        }

      }

    }

class Printer {

    boolean isOdd;

    Printer(boolean isOdd){
        this.isOdd = isOdd;
    }

    synchronized void printEven(int number) {

        while(isOdd){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Even:"+number);
        isOdd = true;
        notifyAll();
    }

    synchronized void printOdd(int number) {
        while(!isOdd){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Odd:"+number);
        isOdd = false;
        notifyAll();
    }

}

Can someone help me in fixing this?

EDIT Expected result: Odd:1 Even:2 Odd:3 Even:4 Odd:5 Even:6 Odd:7 Even:8 Odd:9

30条回答
做个烂人
2楼-- · 2019-01-04 10:59

This program can be written in two ways-

  • Using Wait and Notify for inter thread communication. But the disadvantage of this is that if the number of threads increase more than two then it cannot be used.
  • Using Java Semaphore for inter thread communication. This is more extendable and can be modified even if question is further modified to as about 3 Threads-

package com.effectivecorejava; import java.util.concurrent.Semaphore;

public class SemaphoreExample {

public static void main(String[] args) {

    //We dont want the even number printed first so the initial permit for this semaphore is 0.
    Semaphore evenSemaphore = new Semaphore(0);
    //We want to print the odd number first so the initial permit for this semaphore is 1.
    Semaphore oddSemaphore = new Semaphore(1);

    PrintOddNumber printOddNumber = new PrintOddNumber(evenSemaphore, oddSemaphore);
    PrintEvenNumber printEvenNumber = new PrintEvenNumber(evenSemaphore, oddSemaphore);

    new Thread(printOddNumber, "Print Odd").start();
    new Thread(printEvenNumber, "Print Odd").start();
}

}

class PrintEvenNumber implements Runnable {

Semaphore sempahoreEven;
Semaphore sempahoreOdd;

public PrintEvenNumber(Semaphore sempahoreEven, Semaphore sempahoreOdd) {
    super();
    this.sempahoreEven = sempahoreEven;
    this.sempahoreOdd = sempahoreOdd;
}

@Override
public void run() {
    for (int i = 2;; i = i + 2) {
        try {
            //This will decrement the permit used by the even semaphore to 0. 
            sempahoreEven.acquire();
            System.out.println(i);
            //This will increment the permit used by odd semaphore by 1.
            sempahoreOdd.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

}

class PrintOddNumber implements Runnable {

Semaphore sempahoreEven;
Semaphore sempahoreOdd;

public PrintOddNumber(Semaphore sempahoreEven, Semaphore sempahoreOdd) {
    this.sempahoreEven = sempahoreEven;
    this.sempahoreOdd = sempahoreOdd;
}

@Override
public void run() {
    for (int i = 1;; i = i + 2) {
        try {
            //This will decrement the permit used by the odd semaphore to 0. 
            sempahoreOdd.acquire();

            Thread.sleep(1000);
            System.out.println(i);
            //This will increment the permit used by even semaphore by 1.
            sempahoreEven.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}

}
查看更多
做自己的国王
3楼-- · 2019-01-04 10:59
package programs.multithreading;

public class PrintOddEvenNoInSequence {

final int upto;
final PrintOddEvenNoInSequence obj;
volatile boolean oddFlag,evenFlag;
public PrintOddEvenNoInSequence(int upto){
    this.upto = upto;
    obj = this;
    oddFlag = true;
    evenFlag = false;
}
void printInSequence(){

    Thread odd = new Thread(new Runnable() {
        @Override
        public void run() {
            for(int i = 1; i <= upto; i = i + 2){
                synchronized (obj) {
                    while(!oddFlag){
                        try {
                            obj.wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    System.out.println("Odd:"+i);
                    oddFlag = false;
                    evenFlag = true;
                    obj.notify();
                }
            }
        }
    });

    Thread even = new Thread(new Runnable() {
        @Override
        public void run() {
            for(int i = 2; i <= upto; i = i + 2){
                synchronized (obj) {
                    while(!evenFlag){
                        try {
                            obj.wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    System.out.println("Even:"+i);
                    oddFlag = true;
                    evenFlag = false;
                    obj.notify();
                }
            }
        }
    });

    odd.start();
    even.start();

}
public static void main(String[] args) {
    new PrintOddEvenNoInSequence(100).printInSequence();
}
}
查看更多
4楼-- · 2019-01-04 11:00

This code will also work fine.

class Thread1 implements Runnable {

    private static boolean evenFlag = true;

    public synchronized void run() {
        if (evenFlag == true) {
            printEven();
        } else {
           printOdd();
        }
    }

    public void printEven() {
        for (int i = 0; i <= 10; i += 2) {
            System.out.println(i+""+Thread.currentThread());
        }
        evenFlag = false;
    }

    public  void printOdd() {
        for (int i = 1; i <= 11; i += 2) {
            System.out.println(i+""+Thread.currentThread());
        }
        evenFlag = true;
    }
}

public class OddEvenDemo {

    public static void main(String[] args) {

        Thread1 t1 = new Thread1();
        Thread td1 = new Thread(t1);
        Thread td2 = new Thread(t1);
        td1.start();
        td2.start();

    }
}
查看更多
男人必须洒脱
5楼-- · 2019-01-04 11:03
public class ThreadEvenOdd {
  static int cnt=0;
  public static void main(String[] args) {

    Thread t1 = new Thread(new Runnable() {

      @Override
      public void run() {
        synchronized(this) {
          while(cnt<101) {
            if(cnt%2==0) {
              System.out.print(cnt+" ");
              cnt++;
            }
            notifyAll();
          }
        }
      }

    });
    Thread t2 = new Thread(new Runnable() {

      @Override
      public void run() {
        synchronized(this) {
          while(cnt<101) {
            if(cnt%2==1) {
              System.out.print(cnt+" ");
              cnt++;
            }
            notifyAll();
          }
        }
      }
    });

    t1.start();
    t2.start();
  }
}
查看更多
Root(大扎)
6楼-- · 2019-01-04 11:03
        public class OddAndEvenThreadProblems {
            private static Integer i = 0;

            public static void main(String[] args) {
                new EvenClass().start();
                new OddClass().start();

            }

            public static class EvenClass extends Thread {

                public void run() {
                    while (i < 10) {
                        synchronized (i) {
                            if (i % 2 == 0 ) {
                                try {
                                    Thread.sleep(1000);
                                    System.out.println(" EvenClass " + i);
                                    i = i + 1;
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                        }
                    }
                }
            }

            public static class OddClass extends Thread {

                @Override
                public void run() {
                    while (i < 10) {
                        synchronized (i) {
                            if (i % 2 == 1) {
                                try {
                                    Thread.sleep(1000);
                                    System.out.println(" OddClass  " + i);
                                    i = i + 1;
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                    }
                }
            }
        }
    }





OUTPUT will be :- 

 EvenClass 0
 OddClass  1
 EvenClass 2
 OddClass  3
 EvenClass 4
 OddClass  5
 EvenClass 6
 OddClass  7
 EvenClass 8
 OddClass  9
查看更多
smile是对你的礼貌
7楼-- · 2019-01-04 11:03

See the Clean implementation

public class PrintOddEvenByTwoThreads {
    static int number = 1;
    static Thread odd;
    static Thread even;
    static int max = 10;

    static class OddThread extends Thread {
        @Override
        public void run() {
            while (number <= max) {
                if (number % 2 == 1) {
                    System.out.println(Thread.currentThread() + "" + number++);
                } else {

                    synchronized (odd) {
                        synchronized (even) {
                            even.notify();
                        }
                        try {
                            wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    static class EvenThread extends Thread {
        @Override
        public void run() {
            while (number <= max) {
                if (number % 2 == 0) {
                    System.out.println(Thread.currentThread() + "" + number++);
                } else {

                    synchronized (even) {
                        synchronized (odd) {
                            odd.notify();
                        }
                        try {
                            wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        odd = new OddThread();
        even = new EvenThread();
        odd.start();
        even.start();
    }
}
查看更多
登录 后发表回答