23

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

6
  • 1
    What is the actual result and what is your expected result?
    – Supericy
    May 22, 2013 at 10:44
  • 3
    number starts at 1, and you only ever increment it by 2. Therefore it will never be even. May 22, 2013 at 10:47
  • 8
    This is not a debugging service...
    – Bohemian
    May 22, 2013 at 11:18
  • 6
    For every student who comes here: Please tell your instructor that while this exercise might teach you something about how to control threads, it is a really horrible example of why to use threads. If you want a program to do certain things (e.g., print numbers) in a certain order (e.g., 1, 2, 3, ...); then the absolutely best way to do it is to do those things in a single thread. Every multi-threaded program requires some synchronization between threads, but the more synchronization you use, the less benefit you get from threading. This program actually gets negative benefit. Mar 23, 2016 at 14:14
  • There is no reason why the threads should print numbers in alternation, even leaving aside the error about the increment. Your expectations are astray, as is the uncited 'some other piece of code'. SO is not a validation service for arbitrary Internet junk.
    – user207421
    Jun 26, 2016 at 2:09

42 Answers 42

1
2
0

This solution works for me (Java 8 and above used Lamda expression)

public class EvenOddUsingThread {

    static int number = 100;
    static int counter = 1;

    public static void main(String[] args) {
        EvenOddUsingThread eod = new EvenOddUsingThread();
        Thread t1 = new Thread(() -> eod.printOdd());
        Thread t2 = new Thread(() -> eod.printEven());
        t1.start();
        t2.start();
    }

    public void printOdd() {
        synchronized (this) {
            while (counter < number) {
                if (counter % 2 == 0) {
                    try {
                        wait();
                    } catch (InterruptedException e) {
                    }
                }
                // Print the number
                System.out.println(counter + " Thread Name: " + Thread.currentThread().getName());
                // Increment counter
                counter++;
                // Notify to second thread
                notify();
            }
        }
    }

    public void printEven() {
        synchronized (this) {
            while (counter < number) {
                if (counter % 2 == 1) {
                    try {
                        wait();
                    } catch (InterruptedException ignored) {
                    }
                }
                // Print the number
                System.out.println(counter + " Thread Name: " + Thread.currentThread().getName());
                // Increment counter
                counter++;
                // Notify to second thread
                notify();
            }
        }
    }

}
0

The solution below is using java 8 completable future and executor service to print even and odd numbers using two threads.

ExecutorService firstExecutorService = Executors.newSingleThreadExecutor(r -> {
        Thread t = new Thread(r);
        t.setName("first");
        return t;
    });

    ExecutorService secondExecutorService = Executors.newSingleThreadExecutor(r -> {
        Thread t = new Thread(r);
        t.setName("second");
        return t;
    });

    IntStream.range(1, 101).forEach(num -> {

        CompletableFuture<Integer> thenApplyAsync = CompletableFuture.completedFuture(num).thenApplyAsync(x -> {

            if (x % 2 == 1) {
                System.out.println(x + " " + Thread.currentThread().getName());
            }
            return num;
        }, firstExecutorService);

        thenApplyAsync.join();

        CompletableFuture<Integer> thenApplyAsync2 = CompletableFuture.completedFuture(num).thenApplyAsync(x -> {
            if (x % 2 == 0) {
                System.out.println(x + " " + Thread.currentThread().getName());
            }
            return num;
        }, secondExecutorService);

        thenApplyAsync2.join();
    });

    firstExecutorService.shutdown();
    secondExecutorService.shutdown();

The below is the console log of it.
enter image description here

0

We can print odd and even using two separate threads using CompletableFuture as well:

import java.util.concurrent.CompletableFuture;
import java.util.function.IntPredicate;
import java.util.stream.IntStream;

public class OddEvenBy2Thread {

    private static Object object = new Object();

    private static IntPredicate evenCondition = e -> e % 2 == 0;
    private static IntPredicate oddCondition = e -> e % 2 != 0;

    public static void main(String[] args) throws InterruptedException {

        // Odd number printer
        CompletableFuture.runAsync(() -> OddEvenBy2Thread.printNumber(oddCondition));

        // Even number printer
        CompletableFuture.runAsync(() -> OddEvenBy2Thread.printNumber(evenCondition));

        Thread.sleep(1000);
    }

    public static void printNumber(IntPredicate condition){
        IntStream.rangeClosed(1, 10).filter(condition).forEach(OddEvenBy2Thread::execute);
    }

    public static void execute(int num){
        synchronized (object){
            try{
                System.out.println(Thread.currentThread().getName()+" : "+num);
                object.notify();
                object.wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }

    }
}

-1

public class EvenOddex {

public static class print {

    int n;
    boolean isOdd = false;

    synchronized public void printEven(int n) {

        while (isOdd) {
            try {
                wait();
            } catch (InterruptedException ex) {
                Logger.getLogger(EvenOddex.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        System.out.print(Thread.currentThread().getName() + n + "\n");

        isOdd = true;
        notify();
    }

    synchronized public void printOdd(int n) {
        while (!isOdd) {
            try {
                wait();
            } catch (InterruptedException ex) {
                Logger.getLogger(EvenOddex.class.getName()).log(Level.SEVERE, null, ex);
            }
        }


        System.out.print(Thread.currentThread().getName() + n + "\n");
        isOdd = false;
        notify();



    }
}

public static class even extends Thread {

    print po;

    even(print po) {

        this.po = po;

        new Thread(this, "Even").start();

    }

    @Override
    public void run() {


        for (int j = 0; j < 10; j++) {
            if ((j % 2) == 0) {
                po.printEven(j);
            }
        }

    }
}

public static class odd extends Thread {

    print po;

    odd(print po) {

        this.po = po;
        new Thread(this, "Odd").start();
    }

    @Override
    public void run() {

        for (int i = 0; i < 10; i++) {

            if ((i % 2) != 0) {
                po.printOdd(i);
            }
        }

    }
}

public static void main(String args[]) {
    print po = new print();
    new even(po);
    new odd(po);

}

}

-1
public class Multi extends Thread{  
    public static int a;
    static{a=1;}
    public void run(){  
        for(int i=1;i<5;i++){  
        System.out.println("Thread Id  "+this.getId()+"  Value "+a++);
        try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}  

        }  
    }  
public static void main(String args[]){  
       Multi t1=new Multi();  
       Multi t2=new Multi();  

      t1.start();  
      t2.start();  
    }  
}  
1
  • The correctness of your program is dependent upon 'Thread.sleep();' that you have written over there. It will give unpredictable results. The idea is to create a program that will yield the desired result with certainty.
    – de_xtr
    Oct 28, 2015 at 7:44
-1
public class PrintOddEven {
private static class PrinterThread extends Thread {

    private static int current = 0;
    private static final Object LOCK = new Object();

    private PrinterThread(String name, int number) {
        this.name = name;
        this.number = number;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (LOCK) {
                try {
                    LOCK.wait(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if (current < number) {
                    System.out.println(name + ++current);
                } else {
                    break;
                }

                LOCK.notifyAll();
            }
        }
    }

    int number;
    String name;
}

public static void main(String[] args) {
    new PrinterThread("thread1 : ", 20).start();
    new PrinterThread("thread2 : ", 20).start();
}
}
-1

public class Solution {

 static class NumberGenerator{

     private static volatile boolean printEvenNumber = false;


     public  void printEvenNumber(int i) {
         synchronized (this) {
             if(!printEvenNumber) {
                 try {
                     wait();
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
             }
             System.out.println(i);
             printEvenNumber = !printEvenNumber;
             notify();
         }
     }

     public  void printOddNumber(int i ) {
            synchronized (this) {
                if(printEvenNumber) {
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.println(i);
                printEvenNumber = !printEvenNumber;
                notify();
            }
     }

}

static  class OddNumberGenerator implements Runnable{
    private NumberGenerator numberGenerator;

    public OddNumberGenerator(NumberGenerator numberGenerator) {
        this.numberGenerator = numberGenerator;
    }

    @Override
    public void run() {
        for(int i  = 1; i <100; i = i + 2) {
            numberGenerator.printOddNumber(i);
        }
    }
}

static class EvenNumberGenerator implements Runnable {
    private NumberGenerator numberGenerator;

    public EvenNumberGenerator(NumberGenerator numberGenerator) {
        this.numberGenerator = numberGenerator;
    }

    @Override
    public void run() {
        for (int i = 2; i <= 100; i =  i + 2) {
           numberGenerator.printEvenNumber(i);
        }
    }
}


public static void main(String[] args) {
    NumberGenerator ng = new NumberGenerator();
    OddNumberGenerator oddNumberGenerator = new OddNumberGenerator(ng);
    EvenNumberGenerator evenNumberGenerator = new EvenNumberGenerator(ng);
    new Thread(oddNumberGenerator).start();
    new Thread(evenNumberGenerator).start();

}

}

-1
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();
}
}
1
  • While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
    – J. Chomel
    Apr 20, 2017 at 5:58
-1

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();
    }
}
-1

1- The number is initialized with 1 and isOdd flag is set to false. set isOdd to true

2- Increment should be by 1 (not by 2) i.e number+=1;

-2
import java.util.concurrent.Semaphore;


public class PrintOddAndEven {

private static class OddThread extends Thread {
    private Semaphore semaphore;
    private Semaphore otherSemaphore;
    private int value = 1;

    public  OddThread(Semaphore semaphore, Semaphore otherSemaphore) {
        this.semaphore = semaphore;
        this.otherSemaphore = otherSemaphore;
    }

    public void run() {
        while (value <= 100) {
            try {
                // Acquire odd semaphore
                semaphore.acquire();
                System.out.println(" Odd Thread " + value + " " + Thread.currentThread().getName());

            } catch (InterruptedException excetion) {
                excetion.printStackTrace();
            }
            value = value + 2;
            // Release odd semaphore
            otherSemaphore.release();
        }
    }
}


private static class EvenThread extends Thread {
    private Semaphore semaphore;
    private Semaphore otherSemaphore;

    private int value = 2;

    public  EvenThread(Semaphore semaphore, Semaphore otherSemaphore) {
        this.semaphore = semaphore;
        this.otherSemaphore = otherSemaphore;
    }

    public void run() {
        while (value <= 100) {
            try {
                // Acquire even semaphore
                semaphore.acquire();
                System.out.println(" Even Thread " + value + " " + Thread.currentThread().getName());

            } catch (InterruptedException excetion) {
                excetion.printStackTrace();
            }
            value = value + 2;
            // Release odd semaphore
            otherSemaphore.release();
        }
    }
}


public static void main(String[] args) {
    //Initialize oddSemaphore with permit 1
    Semaphore oddSemaphore = new Semaphore(1);
    //Initialize evenSempahore with permit 0
    Semaphore evenSempahore = new Semaphore(0);
    OddThread oddThread = new OddThread(oddSemaphore, evenSempahore);
    EvenThread evenThread = new EvenThread(evenSempahore, oddSemaphore);
    oddThread.start();
    evenThread.start();
    }
}
1
  • Added comments to the code. Program prints 1 to 100, shared between two threads.
    – Srivathsan
    Apr 26, 2017 at 5:36
-2

Simple Solution below:-

package com.test;

class MyThread implements Runnable{

    @Override
    public void run() {
        int i=1;
        while(true) {
            String name=Thread.currentThread().getName();
            if(name.equals("task1") && i%2!=0) {
                System.out.println(name+"::::"+i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else if(name.equals("task2") && i%2==0){
                System.out.println(name+"::::"+i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            i++;
        }

    }

    public static void main(String[] args) {

        MyThread task1=new MyThread();
        MyThread task2=new MyThread();

        Thread t1=new Thread(task1,"task1");
        Thread t2=new Thread(task2,"task2");

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

    }

}
1
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.