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
Here is the code which I made it work through a single class
Output:
Simple solution :)
This is my solution to the problem. I have two classes implementing
Runnable
, one prints odd sequence and the other prints even. I have an instance ofObject
, that I use for lock. I initialize the two classes with the same object. There is asynchronized block
inside the run method of the two classes, where, inside a loop, each method prints one of the numbers, notifies the other thread, waiting for lock on the same object and then itself waits for the same lock again.The classes :
The upper limit in my example is 10. Once the odd thread prints 9 or the even thread prints 10, then we don't need any of the threads to wait any more. So, we can handle that using one
if-block
. Or, we can use the overloadedwait(long timeout)
method for the wait to be timed out. One flaw here though. With this code, we cannot guarantee which thread will start execution first.Another example, using Lock and Condition
}
Found the solution. Someone looking for solution to this problem can refer :-)
This gives output like:
You can use the following code to get the output with creating two anonymous thread classes.