I was asked below question in an interview where I need to print out even and odd numbers using two threads so I came up with below code one without synchronization and other with synchronization.
/**
* Without synchronization
*
*/
class Print {
private static final int MAX = 10;
private static int count = 1;
private boolean isOdd = true;
public void printEven() {
while (true) {
if (count > MAX)
break;
if (!isOdd) {
System.err.println(Thread.currentThread().getName() + " : " + count++);
isOdd = true;
}
}
}
public void printOdd() {
while (true) {
if (count > MAX)
break;
if (isOdd) {
System.err.println(Thread.currentThread().getName() + " : " + count++);
isOdd = false;
}
}
}
}
/**
* Using synchronization
*
*/
class Print2 {
private static final int MAX = 10;
private static int count = 1;
private Object obj = new Object();
public void printEven() {
while (true) {
if (count > MAX)
break;
synchronized (obj) {
System.err.println(Thread.currentThread().getName() + " : " + count++);
obj.notify();
try {
obj.wait();
} catch (InterruptedException e) {
}
}
}
}
public void printOdd() {
while (true) {
if (count > MAX)
break;
synchronized (obj) {
System.err.println(Thread.currentThread().getName() + " : " + count++);
obj.notify();
try {
obj.wait();
} catch (InterruptedException e) {
}
}
}
}
}
public class PrintEvenOddTester {
public static void main(String[] args) {
Print p = new Print();
Thread t1 = new Thread(() -> p.printEven());
t1.setName("EVEN");
Thread t2 = new Thread(() -> p.printOdd());
t2.setName("ODD");
t1.start();
t2.start();
}
}
I wanted to check whether there is any better or efficient way to do these kind of tasks? I ran both the code and it works fine so wanted to check if everything looks good from thread safety and synchronization perspective.
Since in my above code, I am using while(true) loop which will take some CPU's so I am not sure whether this is the best way to do it?
count++andisOdd = ..., the whole system breaks. Your second version does not even work at all. Sorry, this is offtopic for codereview, as we only review working code here. \$\endgroup\$while(true)loop which will take some CPU" Any operation will 'take' some CPU or it wouldn't do us much good, would it? \$\endgroup\$