You can use the lock variables "a" and "b" and synchronize them to lock the "critical section" in the reverse order. For example. Notify βaβ, then block βbβ, βPRINTβ, notify βbβ, then block βaβ.
Please read the following code: -
public class EvenOdd { static int a = 0; public static void main(String[] args) { EvenOdd eo = new EvenOdd(); A aobj = eo.new A(); B bobj = eo.new B(); aobj.a = Lock.lock1; aobj.b = Lock.lock2; bobj.a = Lock.lock2; bobj.b = Lock.lock1; Thread t1 = new Thread(aobj); Thread t2 = new Thread(bobj); t1.start(); t2.start(); } static class Lock { final static Object lock1 = new Object(); final static Object lock2 = new Object(); } class A implements Runnable { Object a; Object b; public void run() { while (EvenOdd.a < 10) { try { System.out.println(++EvenOdd.a + " A "); synchronized (a) { a.notify(); } synchronized (b) { b.wait(); } } catch (InterruptedException e) { e.printStackTrace(); } } } } class B implements Runnable { Object a; Object b; public void run() { while (EvenOdd.a < 10) { try { synchronized (b) { b.wait(); System.out.println(++EvenOdd.a + " B "); } synchronized (a) { a.notify(); } } catch (InterruptedException e) { e.printStackTrace(); } } } }
}
OUTPUT: - 1 A 2 B 3 A 4 B 5 A 6 B 7 A 8 B 9 A 10 B
AkashPushPopStack
source share