Java multithreading BASICS (3) traditional Java thread mutex technology, multi-thread mutex
Java multithreading BASICS (iii) traditional Java thread mutex Technology
Java threads are mutually exclusive mainly through the synchronized keyword. The following sample code demonstrates the basic usage of several synchronized keywords.
Package cn. king; public class TraditionalThreadSynchronized {public static void main (String [] args) {new TraditionalThreadSynchronized (). foo ();} private void foo () {// printer must be final; otherwise, compilation fails. This is mainly to Ensure printer consistency. Final Printer printer = new Printer (); new Thread (new Runnable () {@ Override public void run () {while (true) {try {Thread. sleep (10);} catch (InterruptedException e) {e. printStackTrace ();}/** Cannot refer to a non-final variable printer * inside an inner class defined in a different method * For more information, see java8 lambda expressions (closures) related Knowledge */printer. output ("123456789 ");}}}). start (); new Thread (new Runnable () {@ Override public void run () {while (true) {try {Thread. sleep (10);} catch (InterruptedException e) {e. printStackTrace ();} printer. output ("abcdefghi ");}}}). start ();} static class Printer {String _ lock = ""; public void output (String name) {int len = name. length (); // Synchronous Code block/* Method 1: * use this as the Lock Object. * It is mutually exclusive with the code block or synchronized method that uses this to lock * // synchronized (this) {/* Method 2: * use the Outputer class bytecode object (this object is automatically created by the Virtual Machine) as the Lock Object. * use Outputer. the code block or static synchronized Method of the class lock is mutually exclusive * // synchronized (Outputer. class) {/* method 3: * use a custom object as the lock Object. * The lock Object is mutually exclusive with the code block using _ lock. */synchronized (_ lock) {for (int I = 0; I <len; I ++) {System. out. print (name. charAt (I);} System. out. println () ;}// synchronous method, equivalent to synchronized (this) {}public synchronized void output2 (String name) {int len = name. length (); for (int I = 0; I <len; I ++) {System. out. print (name. charAt (I);} System. out. println ();} // static synchronization method, equivalent to synchronized (Outputer. class) {} public static synchronized void output3 (String name) {int len = name. length (); for (int I = 0; I <len; I ++) {System. out. print (name. charAt (I);} System. out. println ();}}}
The above code shows three basic thread mutex implementations. The following describes the implementation features and application of the three methods.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.