public class ThreadSynchronization {
public static void main(String[] args) throws InterruptedException {
Object lockObject = new Object();
Thread t1 = new Thread(new MyRunnableEven(lockObject));
Thread t2 = new Thread(new MyRunnableOdd(lockObject));
t1.start();
t2.start();
}
}
class MyRunnableEven implements Runnable {
private Object lockObject;
MyRunnableEven(Object lockObject) {
this.lockObject = lockObject;
}
@Override
public void run() {
for (int i = 0; i <= 10; i = i + 2) {
synchronized (lockObject) {
try {
System.out.println("Even " + i);
lockObject.notify();
lockObject.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class MyRunnableOdd implements Runnable {
private Object lockObject;
MyRunnableOdd(Object lockObject) {
this.lockObject = lockObject;
}
@Override
public void run() {
for (int i = 1; i < 10; i = i + 2) {
synchronized (lockObject) {
try {
lockObject.wait();
System.out.println("Odd " + i);
lockObject.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}