[Switch] thread 8 lock, thread
Package com. java. juc;/*** title: Print "one" or "two" ** 1. two common Synchronization Methods, two threads, standard printing, and printing? // One two * 2. added Thread. sleep (3000) to print data to getOne? // Print one two after 3 s * 3. Add the common method getThreee to print? // Print three seconds before one two * 4. two common Synchronization Methods, two number objects, and print? // Print one * 5 after two 3 S. Change getOne () to the static synchronization method, a number object, and print? // Print one * 6 after two 3 S. Modify the two methods as static Synchronization Methods, a number object, and print? // Print one two * 7 after 3 s. modify getOne () to a static synchronization method, and getTwo () to a non-static synchronization method. There are two numbers, one calling one, and one calling two // two 3 s, and then print one * 8. both are changed to static Synchronization Methods. Two numbers call getOne () and one call getTwo () // print one two * @ author Administrator **/public class TestThread8Monitor {public static void main (String [] args) {final Number number Number = new Number (); final Number number2 = new Number (); new Thread (new Runnable () {@ Override public void run () {number. getOne ();}}). start (); new Thread (new Runnable () {@ Override public void run () {number2.getTwo ();}}). start ();/* new Thread (new Runnable () {@ Override public void run () {number. getThree ();}}). start (); */} class Number {public static synchronized void getOne () {try {Thread. sleep (3000);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println ("one");} public static synchronized void getTwo () {System. out. println ("two");} public void getThree () {System. out. println ("three ");}}
Only one object holds the lock at a time. No matter how many methods are available, other threads cannot hold the lock.
Key to thread eight locks:
1. The default lock of non-static methods is this, and the lock of static methods is the corresponding Class instance (Class bytecode ).
2. At a certain time point, only one thread can hold the lock, regardless of several methods.
Reprinted from: http://www.cnblogs.com/wq3435/p/6366913.html