Java multithreaded synchronization

Source: Internet
Author: User

I. Synchronized keywords

Synchronization method

Each object contains a lock (also called a monitor), which is automatically referred to as part of the object (you do not have to write any special code for this). When any synchronized method is called, the object is locked and no other synchronized method of that object can be called, unless the first method completes its work.

The sample code is as follows:

public class Simplethread implements Runnable {private int count = 0, @Overridepublic void Run () {while (true) {try {test () ;} catch (Interruptedexception e) {e.printstacktrace ();}}} Private synchronized void Test () throws Interruptedexception {System.out.println (Thread.CurrentThread (). GetName () + ": "+ count++); Thread.Sleep (100);} public static void Main (string[] args) {simplethread sd = new Simplethread (), for (int i = 0; i < 3; i++) {New Thread (SD ). Start ();}}

Synchronization block

The lock must be acquired on the synchobject before it enters the synchronization block. If the lock has been made by another thread, the block cannot enter and must wait for the lock to be released. In general, the current object is used as a lock.

The sample code is as follows:

public class Simplethread implements Runnable {private int count = 0, @Overridepublic void Run () {while (true) {try {test () ;} catch (Interruptedexception e) {e.printstacktrace ();}}} private void Test () throws Interruptedexception {synchronized (this) {System.out.println (Thread.CurrentThread (). GetName () + ":" + count++);} Thread.Sleep (100);} public static void Main (string[] args) {simplethread sd = new Simplethread (), for (int i = 0; i < 3; i++) {New Thread (SD ). Start ();}}

Note: Synchronization is a high-overhead operation, so you should minimize the content of synchronization. It is usually not necessary to synchronize the entire method, using the synchronized code block to synchronize the key code.

Two. Using special domain variables (volatile)

The volatile keyword provides a lock-free mechanism for accessing domain variables, which is equivalent to telling the virtual machine that the domain might be updated by other threads, so that each time the domain is used it is recalculated instead of using the value in the register. Volatile does not provide any atomic manipulation, nor can it be used to modify a variable of the final type.

public class Simplethread implements Runnable {private volatile int count = 0, @Overridepublic void Run () {while (true) {TR Y {test ();} catch (Interruptedexception e) {e.printstacktrace ();}}} private void Test () throws Interruptedexception {System.out.println (Thread.CurrentThread (). GetName () + ":" + count++); Thread.Sleep (100);} public static void Main (string[] args) {simplethread sd = new Simplethread (), for (int i = 0; i < 3; i++) {New Thread (SD ). Start ();}}

Note: Because the thread execution speed is not the same, the results of the console printing are not all from large to small.

Three. Using the Java.util.concurrent Package

A new java.util.concurrent package has been added in JavaSE5.0 to support synchronization. The Reentrantlock class is a re-entrant, mutex, and lock interface that implements the same basic behavior and semantics as using the Synchronized method, and extends its capabilities.

The sample code is as follows:

Import Java.util.concurrent.locks.lock;import Java.util.concurrent.locks.reentrantlock;public class SimpleThread Implements Runnable {private int count = 0;private lock lock = new Reentrantlock (); @Overridepublic void Run () {while (true {try {test ();} catch (Interruptedexception e) {e.printstacktrace ();}}} private void Test () throws Interruptedexception {lock.lock (); try {System.out.println (Thread.CurrentThread (). GetName ( ) + ":" + count++);} finally {Lock.unlock ();} Thread.Sleep (100);} public static void Main (string[] args) {simplethread sd = new Simplethread (), for (int i = 0; i < 3; i++) {New Thread (SD ). Start ();}}

Four. Managing variables with Threadlocal

If you use threadlocal to manage variables, each thread that uses the variable gets a copy of the variable, and the replicas are independent of each other so that each thread can modify its own copy of the variable without affecting other threads.

The sample code is as follows:

public class Simplethread implements Runnable {private threadlocal<integer> count = new threadlocal<integer> () {@Overrideprotected Integer initialvalue () {return 0;}}; @Overridepublic void Run () {while (true) {try {test ()} catch (Interruptedexception e) {e.printstacktrace ();}}} private void Test () throws Interruptedexception {System.out.println (Thread.CurrentThread (). GetName () + ":" + count.get ( ). ToString ()); Count.set (Count.get () + 1); Thread.Sleep (100);} public static void Main (string[] args) {simplethread sd = new Simplethread (), for (int i = 0; i < 3; i++) {New Thread (SD ). Start ();}}

Java multithreaded synchronization

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.