Java thread (12): synchronization-synchronization method of threads

Source: Internet
Author: User

Ava thread: synchronization of threads-synchronization of threads is a means to ensure safe 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: Identify the competing resource as private; synchronize the code for modifying variables, and use the synchronized keyword to synchronize the method or code. Of course, this is not the only way to control concurrency security. Note: synchronized can only mark non-Abstract methods and 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: thread synchronization ** @ author leizhimin 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. margin (y) ;}} class User {private String code; private int cash; User (String code, int cash) {this. code = code; this. cash = cash;} public S Tring getCode () {return code;} public void setCode (String code) {this. code = code;}/*** business method ** @ param x Add x million */public synchronized void encode (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 String () {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 "21" is added. The current user account balance is: 141 thread E stops running, add "32", the current user account balance is: 173 thread C running ended, add "-80", the current user account balance is: 93 thread B running ended, add "-60", the current user account balance is: 33 thread D run ended, add "-30", the current user account balance is: 3 Process finished with exit code 0 negative teaching material, if synchronization is not performed, remove the synchronized modifier of the prepare (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 is running and "-30" is added. The account balance is: 63 threads B run ended, add "-60", the current user account balance is: 3 threads F run ended, add "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 it is clear that the above result is incorrect. The cause of the error is that multiple threads concurrently access competing resources u, the u attribute is modified. See the importance of synchronization. Note: As shown in the previous article, when the thread exits the synchronization method, the lock of the object to which the method belongs will be released. However, you should also note that, you can also use a specific method to schedule threads in the synchronization method. These methods come from the java. lang. Object Class. Void y () Wake up a single thread waiting on this object monitor. Void policyall () Wake up all threads waiting on this object monitor. Void wait () causes the current thread to wait until other threads call the notify () or yyall () method of this object. Void wait (long timeout) causes the current thread to wait until other threads call the notify () method or notifyAll () method of this object, or exceed the specified time. Void wait (long timeout, int nanos) causes the current thread to wait until other threads call the notify () method or notifyAll () method of this object, or other threads interrupt the current thread, or the actual time has exceeded. 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.

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.