Java thread: synchronization-synchronization method of threads

Source: Internet
Author: User

Thread Synchronization is a means to ensure secure access to competing resources by multiple threads.
Thread Synchronization is a difficult issue in Java multi-thread programming. Developers often don't know what is competing resources, when synchronization needs to be considered, and how to synchronize. Of course, there are no clear answers to these questions, however, there are some principle issues that need to be considered. Are there any problems with changing competing resources?
 
Before this article, see Java thread: synchronization and lock of threads. This article is based on this.
 
For synchronization, you need to complete two operations in the specific Java code:
Mark the resources for competitive access as private;
Use the synchronized keyword to synchronize the code for modifying variables.
Of course, this is not the only way to control concurrency security.
 
Instructions for using synchronized keywords
Synchronized can only mark non-abstract methods, but cannot identify member variables.
 
To demonstrate the use of the synchronization method, a credit card account was built with a credit of 100 million at first, and multiple operations such as overdraft and deposit were simulated. Obviously, the User object of a bank account is a competitive resource, and multiple concurrent operations are performed by the account method begin (int x). Of course, you should add synchronization in this method, and set the account balance as a private variable. Direct access is prohibited.
 
 
/**
* Java thread: synchronization of threads
*
* @ Author leizhimin 2009-11-4 11:23:32
*/
Public class Test {
Public static void main (String [] args ){
User u = new User ("James", 100 );
MyThread t1 = new MyThread ("thread A", u, 20 );
MyThread t2 = new MyThread ("thread B", u,-60 );
MyThread t3 = new MyThread ("thread C", u,-80 );
MyThread t4 = new MyThread ("thread D", u,-30 );
MyThread t5 = new MyThread ("thread E", u, 32 );
MyThread t6 = new MyThread ("thread F", u, 21 );

T1.start ();
T2.start ();
T3.start ();
T4.start ();
T5.start ();
T6.start ();
}
}

Class MyThread extends Thread {
Private User u;
Private int y = 0;

MyThread (String name, User u, int y ){
Super (name );
This. u = u;
This. y = y;
}

Public void run (){
U. Random (y );
}
}

Class User {
Private String code;
Private int cash;

User (String code, int cash ){
This. code = code;
This. cash = cash;
}

Public String getCode (){
Return code;
}

Public void setCode (String code ){
This. code = code;
}

/**
* Business methods
* @ Param x Add x million RMB
*/
Public synchronized void merge (int x ){
Try {
Thread. sleep (10L );
This. cash + = x;
System. out. println (Thread. currentThread (). getName () + "run ended. Add" + x + "". The current user account balance is: "+ cash );
Thread. sleep (10L );
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}

@ Override
Public String toString (){
Return "User {" +
"Code = '" + code +' \ ''+
", Cash =" + cash +
'}';
}
}
 
Output result:
Thread A stops running and adds "20". The current user account balance is 120.
Thread F stops running and adds "21". The current user account balance is 141.
Thread E stops running and adds "32". The current user account balance is 173.
Thread C stops running and adds "-80". The current user account balance is: 93.
Thread B stops running and adds "-60". The current user account balance is: 33.
Thread D stops running and adds "-30". The current user account balance is: 3

Process finished with exit code 0
 
 
The opposite textbook is not synchronized, that is, remove the synchronized modifier of The equals (int x) method and run the program. The result is as follows:
Thread A stops running and adds "20". The current user account balance is: 61.
Thread D stops running and adds "-30". The current user account balance is: 63.
Thread B stops running and adds "-60". The current user account balance is: 3
Thread F stops running and adds "21". The current user account balance is: 61.
Thread E stops running and adds "32". The current user account balance is: 93.
Thread C stops running and adds "-80". The current user account balance is: 61.

Process finished with exit code 0
 
Obviously, the above result is incorrect. The cause of the error is that multiple threads concurrently access the competing resource u, tb and modify the u attribute.
 
See the importance of synchronization.
 
 
Note:
As we can see from the previous article, when the thread exits the synchronization method, it will release the lock of the object to which the method belongs. However, it should be noted that the synchronization method can also use a specific method to schedule the thread. These methods come from the java. lang. Object Class.
 
Void notify ()
Wake up a single thread waiting on this object monitor.
Void policyall ()
Wake up all threads waiting on this object monitor.
Void wait ()
This causes the current thread to wait until other threads call the notify () method or the notifyAll () method of this object.
Void wait (long timeout)
This causes the current thread to wait until other threads call the notify () method or the yyall () method of this object, or exceed the specified time. Www.2cto.com
Void wait (long timeout, int nanos)
This causes the current thread to wait until other threads call the notify () method or yyall () method of this object, or other threads interrupt the current thread, or the thread has exceeded the actual time.
 
In combination with the above methods, it is very important to deal with the problem of multi-thread synchronization and mutex. The famous producer-consumer example is a classic example, which is required for multithreading in any language.


Author: tbwshc

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.