The mutex technology of thread--java thread

Source: Internet
Author: User

Java's multi-threaded mutex is mainly implemented by the Synchronized keyword. A thread is an execution clue, and multiple threads can be understood as multiple execution clues. The process has a separate memory space, while the threads in the process are shared data object resources. In this way, when multiple execution threads are executed alternately under the CPU switch, there will be some disgusting situations, and the result of execution is inconceivable. The first thread does not finish, the CPU switches to another thread execution, and because of the sharing of data resources, the execution of the program will be confusing. The main solution to the mutual exclusion between threads is through synchronized.

The following is an example of the code used in the Intelligence podcast:

package com.cqfczc.util;/** * multi-threaded Mutex technology * @author Zhenliang * */public class threadsynchronized {public static void main (string[] args) {new threadsynchronized (). Testthread (); private void Testthread () {final Outputprinter printer = new Outputprinter (); New Thread (New Runnable () {@Overridepublic vo ID run () {while (true) {try {Thread.Sleep],} catch (Interruptedexception e) {e.printstacktrace ();} Printer.printer ("Wind chimes in Love with Monkeys");}}). Start (); New Thread (New Runnable () {@Overridepublic void run () {while (true) {try {thread.sleep ()} catch (Interruptedex Ception e) {e.printstacktrace ();} Printer.printer ("Monkeys always like Yang Yi");}}). Start ();} 
//multithreading does not apply mutex technology when there is a problem code class outputprinter{public void printer (String name) {if (name = = null) {throw new Nullpointerexc Eption ("parameter cannot be empty!") ");} int namelength = Name.length (); for (int i=0;i<namelength;i++) {System.out.print (Name.charat (i));} System.out.println ();}
}}

1. Custom Objects as lock objects
Implementation Mode : synchronized (< custom lock object >) {...}
applicable: This method is required when there is a need for mutex control between multiple classes (or instances of multiple classes).

Class Outputprinter{private String lock = "Big monkey";p ublic void Printer (String name) {if (name = = null) {throw new Nullpointerexc Eption ("parameter cannot be empty!") ");} int namelength = Name.length (); synchronized (lock) {for (int i=0;i<namelength;i++) {System.out.print (Name.charat (i) );} System.out.println ();}}}

2. Use this as the lock object
Implementation mode:synchronized (this) {...},synchronized instance method;
applicable: applies to the same instance (object) that uses the class as the lock object.

        Synchronization 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 ();        }    

3, with Outputer.class as the lock object
The bytecode object of the Outputer class is automatically loaded by the JVM.
Implementation mode:synchronized (outputer.class) {...}, static Synchronized method
where applicable: All objects that apply to the entire class require mutually exclusive access

        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 ();        }

Summary: A block of code in the same class or a method of mutual exclusion, using this or the class's bytecode as an object lock, when it is necessary to do mutual exclusion between multiple classes (or instances of multiple classes), use a custom object lock or class bytecode object lock; Because the byte code of a class is only one copy of the world, A custom object lock is a member variable inside a class, and the property is the same every time a new object is created.

The mutex technology of thread--java thread

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.