Code:
/** * Two threads loop print output A-b-a-b */public class Aandbfortothread {private static object o = new Object (); private static int flag=0; private static Boolean close=false; Static Class A implements Runnable {@Override public void run () {synchronized (o) { if (flag==0) {flag=1; } while (!close) {System.out.println ("A"); if (flag==1) {try {o.wait ();//Release Lock} catch (Inter Ruptedexception e) {e.printstacktrace (); } o.notify (); }else {o.notify (); try {o.wait (); } catch (Interruptedexception e) {e.printstacktrace (); } } } O.notify (); }}}} Static class B implements Runnable {@Override public void run () {if (flag==0 ) {flag=2; } synchronized (o) {while (!close) {System.out.println ("B"); if (flag==1) {o.notify (); try {o.wait (); } catch (Interruptedexception e) {e.printstacktrace (); }}else{try {o.wait ();//Release lock } catch (Interruptedexception e) {e.printstacktrace (); } o.notify (); }} o.notify (); }}} public static void Main (string[] args) {Thread A = new Thread (NEW A ()); Thread B = new Thread (new B ()); B.start (); A.start (); try {thread.sleep (10l); } catch (Interruptedexception e) {e.printstacktrace (); } close=true; A.interrupt (); B.interrupt (); }}
Output:
2 threads a-b-a-b or b-a-b-a loop output