Java multi-thread synchronized

Source: Internet
Author: User

Three test classes are used to illustrate different scenarios of synchronized applications.

The first is the use of the most basic Synchronized Method.

Package COM. jadyer. thread. sync; /*** Synchronized Method Test * @ see ============================== ========================================================== =========================================== * @ See Overview: every object in Java has a lock or monitor * @ see. Note: When the synchronized keyword modifies a method, this method is a synchronization method * @ see. When a thread accesses the Synchronized Method of an object, it locks the object * @ see any other threads at this time, you cannot access any of the synchronized methods in this object (but the non-synchronized methods in this object are allowed) * @ see until the synchr accessed by this thread After the onized method is executed (or an exception is thrown), the lock of the object will be released * @ see. At this time, any other thread will be allowed to access the synchronized method, or other synchronized methods in this object * @ see ============================ ========================================================== ============================================= * @ See summary: if an object has multiple synchronized methods, a thread has executed a Synchronized Method in the object at a certain time * @ see before the method is completed, other threads cannot access this object, including this method. Any Synchronized Method * @ see focuses on determining who the synchronized lock is. If the method is static, the class object is locked, otherwise, the lock is the current object * @ see ============================== ========================================================== ============================================= * @ see supplement: 1) This is only applicable when multiple threads operate on the same object of the same class. If multiple threads operate on different objects in the same class, this situation does not exist * @ see 2) the volatile variable in Java can also be seen as a "less serious synchronized" * @ See for more information about volatile, please refer to the http://www.ibm.com/developerworks/cn/java/j-jtp06197.html * @ See note: the actual project, more is the Java and Package launched by jdk5.0, that is, Java. util. tool class in the concurrent package * @ see Java. util. concurrent can implement concurrency in a very fine-grained manner. For example, when a thread accesses a locked object, it can wait for 10 seconds * @ see for 10 seconds. If the object is not unlocked, then you can return a timeout prompt to the user, however, synchronized cannot be precisely controlled. * @ see ======================== ========================================================== ================================================== * @ See note: 1) when the synchronized method is executed or an exception occurs, the lock * @ see 2) the data protected by synchronized should be private, otherwise, you do not need to use a method to access the public data. * @ see ====================== ========================================================== ================== =====================================* @ Author macro Yu * @ create Feb 21,201 2 5:29:39 */public class synchronizedtest {public static void main (string [] ARGs) {bank Bank = New Bank (); thread tt11 = new thread (New threadrmb (bank); // a new bank object. There are two bank objects and they belong to different objects of the same class. // verify the Synchronized Method of different objects of the same class in multiple threads, just uncomment the line of code. // bank = New Bank (); thread tt22 = new thread (New threaddollar (bank); tt11.start (); tt22.start ();}} class threadrmb implements runnable {private bank Bank; Public threadrmb (bank Bank) {This. bank = Bank;} @ overridepublic void run () {bank. getrmb () ;}} class threaddollar implements runnable {private bank Bank; Public threaddollar (bank Bank) {This. bank = Bank;} @ overridepublic void run () {bank. getdollar () ;}} class bank {public synchronized void getrmb () {for (INT I = 0; I <20; I ++) {try {thread. sleep (long) (math. random () * 1000);} catch (interruptedexception e) {e. printstacktrace ();} system. out. println (thread. currentthread (). getname () + ":" + I) ;}} public synchronized void getdollar () {for (INT I = 0; I <20; I ++) {try {thread. sleep (long) (math. random () * 1000);} catch (interruptedexception e) {e. printstacktrace ();} system. out. println (thread. currentthread (). getname () + ":" + I );}}}

The following shows how to use synchronized static method.

Package COM. jadyer. thread. sync;/*** synchronized static method test * @ See Note: If a synchronized method is static * @ see, when the thread accesses this method, it does not lock the object where the synchronized method is located, but the class object corresponding to the object where the method is located * @ see because no matter how many objects a class has in Java, these objects correspond to a unique Class Object * @ see. Therefore, when the thread accesses two static synchronized methods of the two objects of the same class respectively, their execution order is also sequential * @ see: a thread executes a static Synchronized Method first. After the execution is complete, the other thread starts to execute another static Synchronized Method * @ See summary: the focus is to determine who the synchronized lock is. If the method is static, the class object is locked, otherwise, the lock is the current object * @ author macro Yu * @ create Feb 21,201 2 5:29:39 */public class synchronizedstatictest {public static void main (string [] ARGs) {bank Bank = New Bank (); thread tt11 = new thread (New threadrmb (bank); thread tt22 = new thread (New threaddollar (bank); tt11.start (); tt22.start () ;}} class threadrmb implements runnable {private bank Bank; Public threadrmb (bank Bank) {This. bank = Bank;} @ overridepublic void run () {bank. getrmb () ;}} class threaddollar implements runnable {private bank Bank; Public threaddollar (bank Bank) {This. bank = Bank;} @ overridepublic void run () {bank. getdollar () ;}} class bank {// verify the difference between the synchronized lock and the class object that locks synchronized. // remove the static keyword, view the console print, that is, public synchronized void getrmb () Public synchronized static void getrmb () {for (INT I = 0; I <20; I ++) {try {thread. sleep (long) (math. random () * 1000);} catch (interruptedexception e) {e. printstacktrace ();} system. out. println (thread. currentthread (). getname () + ":" + I) ;}} public synchronized static void getdollar () {for (INT I = 0; I <20; I ++) {try {thread. sleep (long) (math. random () * 1000);} catch (interruptedexception e) {e. printstacktrace ();} system. out. println (thread. currentthread (). getname () + ":" + I );}}}

The last demonstration is the use of synchronized block.

Package COM. jadyer. thread. sync;/*** synchronized block test * @ author macro Yu * @ create Feb 21,201 2 5:29:39 */public class synchronizedblocktest {public static void main (string [] ARGs) {bank Bank = New Bank (); thread tt11 = new thread (New threadrmb (bank); // if you want to verify that the synchronized (this) lock is the object of the current class, instead of the Class Object of the current class, you can uncomment the line of code and then observe the console printing effect. The result should be the output of two concurrent threads // bank = New Bank (); thread tt22 = new thread (New threaddollar (bank); tt11.start (); tt22.start () ;}} class threadrmb implements runnable {private bank Bank; Public threadrmb (bank Bank) {This. bank = Bank;} @ overridepublic void run () {bank. getrmb () ;}} class threaddollar implements runnable {private bank Bank; Public threaddollar (bank Bank) {This. bank = Bank;} @ overridepublic void run () {bank. getdo Llar () ;}/ *** Bank * @ see description: Writing synchronized blocks: synchronized (object) {// todo ...}, it indicates that the thread locks the object during execution. * @ see usually locks the java. lang. the object is passed in. In fact, any object can be passed in here * @ see because it is a non-practical object, and it only acts as a lock, just like an identifier * @ see: It indicates that if the thread can enter here, that is, run here, lock the object * @ see. If another thread also runs here and finds that the object is locked, it will wait until it is unlocked, to execute the code in the synchronized block * @ see supplement: synchronized (this) indicates locking the object of the current class. Note that it does not lock the Class Object of the current class * @ see synchronized (bank. class) indicates locking the Class Object of the current class * @ author macro Yu * @ create Feb 22,201 2 2:29:16 am */class bank {private object obj11 = new object (); private object obj22 = new object (); Public void getrmb () {// synchronized (obj11) {synchronized (bank. class) {for (INT I = 0; I <20; I ++) {try {thread. sleep (long) (math. random () * 1000);} catch (interruptedexception e) {e. printstacktrace ();} system. out. println (thread. currentthread (). getname () + ":" + I) ;}} public void getdollar () {// synchronized (obj11) {// synchronized (obj22) {synchronized (this) {for (INT I = 0; I <20; I ++) {try {thread. sleep (long) (math. random () * 1000);} catch (interruptedexception e) {e. printstacktrace ();} system. out. println (thread. currentthread (). getname () + ":" + I );}}}}

Related Article

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.