Java multi-Threading vs. concurrency-thread synchronization

Source: Internet
Author: User

1. Multi-threaded shared data

In multi-threaded operations, it is possible for multiple threads to process the same resource at the same time, which is shared data in multiple threads.

2. Thread synchronization

To resolve data sharing problems, you must use synchronization, which means that multiple threads can only have one thread executing the specified code during the same time period, and other threads will wait for the thread to finish before continuing.

Threads to synchronize, there are two ways to do this:

(1) Synchronizing code blocks

Synchronized (the object to synchronize) {

The operation to synchronize;

}

(2) Synchronization method

Public synchronized void Method () {

The operation to synchronize;

}

(3) Lock

3. Synchronization criteria

When writing synchronized fast, there are a few simple guidelines that can be followed to help avoid deadlocks and the risk of performance risks:

(1) Keep the code block short. Move the preprocessing and post-processing that do not follow the thread change out of synchronized fast.

(2) do not block. such as Inputstream.read ().

(3) Do not invoke methods on other objects while holding the lock.

 Packagecom.vince;ImportJava.util.concurrent.locks.ReentrantLock;/*** Thread synchronization: 1. Synchronizing code blocks 2. Synchronization Method 3.Lock * Synchronization will sacrifice performance for security * *@authorAcer **/ Public classThreaddemo { Public Static voidMain (string[] args) {MyThread Mt=NewMyThread (); Thread T1=NewThread (MT); Thread T2=NewThread (MT);        T1.start ();    T2.start (); }            Static classMyThreadImplementsrunnable{Private intFlag; PrivateObject obj=NewObject ();  Public voidrun () {//Synchronizing code blocks            synchronized(obj) {flag=0; System.out.println ("Start a meal" +flag); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO Auto-generated catch blockE.printstacktrace (); } Flag=1; System.out.println ("End of the meal" +flag); }                    }        //synchronization method: A synchronized lock object is the current object         Public synchronized voideat () {flag=0; System.out.println ("Start a meal" +flag); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO Auto-generated catch blockE.printstacktrace (); } Flag=1; System.out.println ("End of the meal" +flag); }                 Public synchronized voidmethod () {System.out.println ("Method2 ..."); }        //Mutual exclusion Lock        Private FinalReentrantlock lock=NewReentrantlock ();  Public voidEat2 () {lock.lock ();//lockedFlag=0; System.out.println ("Start a meal" +flag); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO Auto-generated catch blockE.printstacktrace (); } Flag=1; System.out.println ("End of the meal" +flag); Lock.unlock ();//Unlock        }        }}

Java multi-Threading vs. concurrency-thread 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.