简体   繁体   中英

Java Multithreading Printing Odd and Even Number

i have started learning Threading in java. I have wrriten a code to print odd and even number in sequence order. But the ouput i am getting is twice. Below is my code.

ThreadBasic1.java:

public class ThreadBasic1 {

    public static void main(String[] args) {


       Thread t1 = new Thread(new ThreadImplementation1());
       Thread t2 = new Thread(new ThreadImplementation1());

       t1.start();
       t2.start();

    }
}

ThreadImplementation1.java:

public class ThreadImplementation1 implements Runnable {

    boolean isOdd= false;
    @Override
    public void run() {
        System.out.println("thread started :: Thread name :: " + Thread.currentThread());
        try {
           for(int i = 1 ; i < 10 ; i++) {
               if(i %2 ==0) {
                   printEven(i);
               }
               else {
                   printOdd(i);
               }
           }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }





    synchronized void printEven(int number)throws InterruptedException  {
        while(!isOdd){
            try {

                wait();

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Even:"+number);
        isOdd = false;
        notifyAll();
    }
    synchronized void printOdd(int number) throws InterruptedException {

        while (isOdd) {

            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("Odd :"+number);

        isOdd = true;
        notifyAll();
    }

}

Output:

thread started :: Thread name :: Thread[Thread-1,5,main]
Odd :1
Even:2
Odd :3
Even:4
Odd :5
Even:6
Odd :7
Even:8
Odd :9
thread started :: Thread name :: Thread[Thread-0,5,main]
Odd :1
Even:2
Odd :3
Even:4
Odd :5
Even:6
Odd :7
Even:8
Odd :9

Your problem is simple: you have two threads that do exactly the same: print the numbers from 1 to 9.

Typically, such exercises require you to have slightly different code for each thread. One thread only prints odd numbers, the other thread prints the even ones. Then both threads need to go in lock step, in order to achieve proper 1 2 3 4 output. Or you have "one" thread implementation, but you somehow enable to configure the behavior of that thread.

Thus the answer here is to step back and re-think your whole approach. There is no point in having two threads doing the same . That just means that you repeat some behavior. Instead, figure how to align two different behaviors.

Of course, I will not give you the code for that: the whole point of the exercise is that you turn these ideas into code.

You can use concept of remainder here.

If number%2==1 then Odd will print the number and increment it else will go in the wait state. If number%2==0 then Even will print the number and increment it else will go in the wait state. Let's check with the help of example.

Create a class named “OddEvenRunnable” and implement Runnable interface.

class OddEvenRunnable implements Runnable {
    public int PRINT_NUMBERS_UPTO = 10;
    static int number = 1;
    int remainder;
    static Object lock = new Object();


    public OddEvenRunnable(int remainder) {
        this.remainder = remainder;
    }

    @Override
    public void run() {
        while (number < PRINT_NUMBERS_UPTO) {
            synchronized (lock) {
                while (number % 2 != remainder) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + " " + number);
                number++;
                lock.notifyAll();
            }
        }

    }
}

public class PrintOddEvenMain {

    public static void main(String[] args) {
        OddEvenRunnable oddRunnable = new OddEvenRunnable(1);
        OddEvenRunnable evenRunnable = new OddEvenRunnable(0);


        Thread t1 = new Thread(oddRunnable, "Odd");
        Thread t2 = new Thread(evenRunnable, "Even");

        t1.start();
        t2.start();
    }

}

You should ideally run just 1 thread which does the toggle job b/w even and odd for you.

package com.samples;

public class ThreadBasic1 {
public static void main(String[] args) {
    Thread t1 = new Thread(new ThreadImplementation1());
    Thread t2 = new Thread(new ThreadImplementation1());

    t1.start();
    //t2.start();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM