Java thread Synchronization

Source: Internet
Author: User

Java thread synchronization is essentially a logic to conform to: lock------> Modify------> Release lock

1. Synchronizing code blocks

Examples are as follows:

 Public classSyncBlock {Static classDatawrap {inti; }        Static classSyncblockthreadextendsThread {PrivateDatawrap date;  PublicSyncblockthread (Datawrap datawrap) { This. Date =Datawrap; } @Override Public voidrun () { for(inti = 0; I < 10; i++) {                synchronized(date) {date.i++; Try{sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (GetName ()+ " " +date.i); }            }        }    }         Public Static voidMain (string[] args) {//Multi-threaded implementation variable I add one output sequentiallyDatawrap Datawrap =NewDatawrap (); NewSyncblockthread (Datawrap). Start (); NewSyncblockthread (Datawrap). Start (); NewSyncblockthread (Datawrap). Start (); }}

In the example, you want to output integers sequentially in order.

Typically, a synchronous code block is an object that needs to be locked, typically a shared resource that requires concurrent access, and any thread locks the resource first before modifying the specified resource, and other threads cannot modify the resource during the lock. This ensures the security of the thread. Another thread does not give up a resource lock when it calls sleep or yield.

2. Synchronization method

 Public classSyncmethod {Static classdatawrap{inti;  Public synchronized voidValuegrow () {i++; Try{Thread.Sleep (1); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+ " " +i); }    }        Static classSyncmethodthreadextendsThread {datawrap datawrap;  PublicSyncmethodthread (Datawrap datawrap) { This. Datawrap =Datawrap; } @Override Public voidrun () { for(inti = 0; I < 10; i++) {datawrap.valuegrow (); }        }    }         Public Static voidMain (string[] args) {//achieve sequential growth and output the I in DatawrapDatawrap Datawrap=NewDatawrap (); NewSyncmethodthread (Datawrap). Start (); NewSyncmethodthread (Datawrap). Start (); NewSyncmethodthread (Datawrap). Start (); }}

The synchronization method is a method that is decorated with the Synchronized keyword, and the synchronization method locks the object itself, so that when a thread invokes the synchronization method of an object, if another thread calls the other synchronization methods of the object, it still waits to release the lock on the object because the object is locked.

3. Synchronous lock

Synchronization locks are implemented by defining a synchronization lock object, in which case the lock object is used by the synchronization latch to act.

ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock; Public classSyncLock {Static classdatawrap{Lock Lock=NewReentrantlock (); inti;  Public voidValuegrow () {lock.lock (); Try{i++; Try{Thread.Sleep (1); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+ " " +i); } finally{lock.unlock (); }                    }    }        Static classSynclockthreadextendsThread {datawrap datawrap;  PublicSynclockthread (Datawrap datawrap) { This. Datawrap =Datawrap; } @Override Public voidrun () { for(inti = 0; I < 10; i++) {datawrap.valuegrow (); }        }    }         Public Static voidMain (string[] args) {//achieve sequential growth and output the I in DatawrapDatawrap Datawrap=NewDatawrap (); NewSynclockthread (Datawrap). Start (); NewSynclockthread (Datawrap). Start (); NewSynclockthread (Datawrap). Start (); }}

Thread synchronization with lock objects is more flexible, some locks have some specific features, which compare commonly used readwritelock read-write locks, Reentrantlock can be re-entered locks.

Java 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.