/*** Programme One * *@authorLY*/ Public classLockObject { PublicString Lockname; Publiclockobject () {} Publiclockobject (String lockname) { This. Lockname =Lockname; } PublicString Getlockname () {returnLockname; } Public voidsetlockname (String lockname) { This. Lockname =Lockname; }} Public classMyThreadImplementsRunnable {PrivateString name; PrivateString Next; PrivateLockObject lock; MyThread (string name, string next, LockObject lock) { This. Name =name; This. Next =Next; This. Lock =lock; } /*** Three threads start at the same time: * 1.new thread (new MyThread ("A", "B", data)). Start (); * 2.new Thread (new MyThread ("B", "C", data)). Start (); * 3.new Thread (new MyThread ("C", "A", data)). Start (); * Enter the loop at the same time: * Previous Data data = new data ("A"); * So Data=a * The first thread satisfies the condition and enters the synchronization method: Print A, set data=b,count=2 * The second thread does not meet the condition, enters an infinite loop, count=3 * The third thread does not meet the conditions, enters the infinite loop, count=3 * Data=b * The second thread satisfies the condition and enters the synchronization method: Print B, set data=c,count=2 * The first thread does not meet the condition, enters an infinite loop, count=2 * The third thread does not meet the condition, enters the infinite loop, count=3 * Data=c * The third thread satisfies the condition and enters the synchronization method: Print C, set data=a,count=2 * The first thread does not meet the condition, enters an infinite loop, count=2 * The second thread does not meet the condition, enters the infinite loop, count=2 * * Once again Data=a * starting from the first thread, three threads meet the criteria in turn and run again, count=1 * * Print Result: ABCABCABC*/ Public voidrun () {intCount = 3; while(Count > 0) { if(Lock.getlockname (). Equals (name)) {synchronized(lock) {System.out.print (name); Lock.setlockname (next); Count--; } } } } Public Static voidMain (string[] args)throwsinterruptedexception {lockobject data=NewLockObject ("A"); NewThread (NewMyThread ("A", "B", data)). Start (); NewThread (NewMyThread ("B", "C", data)). Start (); NewThread (NewMyThread ("C", "A", data)). Start (); }}
Java multithreaded Print ABC