PackageCom.java.juc;/*** Title: Judging print "One" or "two" * 1. Two common sync methods, two threads, standard print, print? One, 2. Add Thread.Sleep (3000) to GetOne () to print? Print one 3 after 3s. New normal method Getthreee printing? Print three three seconds and print one two * 4. Two common synchronization methods, two number objects, printing? Print one * 5 after 3s. Modify GetOne () as a static synchronization method, a Number object, to print? Two 3s print one * 6. Modify two methods are static synchronization method, a Number object, print? 3s print One Two * 7. Modify GetOne () as a static synchronization method, Gettwo () is a non-static synchronization method, two number, a call to one, a call to two//two 3s after the printing of a * 8. Two are changed to the static synchronization method, two Numbe R One call GetOne (), one call to Gettwo ()//3s after a single@authorAdministrator **/ Public classTestthread8monitor { Public Static voidMain (string[] args) {FinalNumber number =NewNumber (); FinalNumber number2 =NewNumber (); NewThread (NewRunnable () {@Override Public voidrun () {number.getone (); }}). Start (); NewThread (NewRunnable () {@Override Public voidrun () {number2.gettwo (); }}). Start (); /*New Thread (new Runnable () {@Override public void run () {number.getthree (); }}). Start ();*/ }}classnumber{ Public Static synchronized voidGetOne () {Try{Thread.Sleep (3000); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("One"); } Public Static synchronized voidGettwo () {System.out.println ("Both"); } Public voidGetthree () {System.out.println ("Three"); }}
Only one object holds a lock at a time, no matter how many methods, no other thread can hold the lock
Key To Line Cheng:
1. The lock of the non-static method defaults to this, and the static method's lock is the corresponding class instance (the bytecode of the class).
2. Within a certain moment, only one thread can hold a lock, no matter how many methods.
Java Multithreaded Line Cheng