Multithreading (one) thread synchronization

Source: Internet
Author: User

One, the thread synchronization has the following methods

1, using synchronized to implement synchronization method;

2, using non-dependent properties to achieve synchronization;

3, use the condition in the synchronous code block;

4, using the lock to achieve synchronization;

5, using read-write synchronous data access;

6, change the fairness of the lock;

7, the use of multiple conditions in the lock;

One of the most common concurrency programming scenarios is when multiple threads of execution share one resource. This is often the case in concurrent applications where multiple threads read or write the same data, or access the same file or database connection. To prevent these shared resources from potentially occurring errors or inconsistent data, we must implement mechanisms to prevent these errors from occurring.

In order to solve these problems, the concept of critical area (Critical section) was introduced. A critical section is a block of code that accesses a shared resource, which allows only one thread to execute at the same time.

Java provides a synchronization mechanism that, when a thread attempts to access a critical section, it uses a synchronization mechanism to see if another thread has entered the critical section. If no other thread enters the critical section, it is suspended by the synchronization mechanism until the incoming thread leaves the critical section. If more than one thread waits to enter the critical section, the JVM chooses one and the rest waits.

Second, using synchronized to implement synchronization method

Each method declared with the Synchronized keyword is a critical section. In Java, the critical section of the same object, at the same time, only one allowed to be accessed.

Static methods have different behaviors. Static methods declared with the Synchronized keyword can only be accessed by one thread of execution, but other threads have access to the non-static method of the object. You must be very cautious about this because two threads can access the two different synchronized methods of an object at the same time, that is, one is a static method and the other is a non-static method. If all two methods change the same data, there will be errors with inconsistent data.

Case:

1 //Create an account class called Account, which is a bank accounts model with only a double type of attribute balance2  Public classAccount {3 4     Private Doublebalance;5 6     //Implement the GetBalance (), Setbalance () method to write and read the value of the balance balance. 7      Public Doublegetbalance ()8     {9         returnbalance;Ten     } One  A      Public voidSetbalance (Doublebalance) -     { -          This. Balance =balance; the     } -  -     /** - * Implement the Addamount () method. It adds the incoming quantity to the balance balance, + * and at the same time only one thread is allowed to change this value, - * So we use the Synchronized keyword to mark this method as a critical section.  +      * @paramAmount A      */ at      Public synchronized voidAddamount (Doubleamount) -     { -         DoubleTMP =balance; -         Try { -TimeUnit.MILLISECONDS.sleep (10); -}Catch(interruptedexception e) { in e.printstacktrace (); -         } toTMP + =amount; +Balance =tmp; -     } the     /** * * Implement the Subtranctamount () method. It will deduct the incoming quantity from the balance, $ * and at the same time only one thread is allowed to change this value,Panax Notoginseng * So we use the Synchronized keyword to mark this method as a critical section.  -      * @paramAmount the      */ +      Public synchronized voidSubtranctamount (Doubleamount) A     { the         DoubleTMP =balance; +         Try { -TimeUnit.MILLISECONDS.sleep (10); $}Catch(interruptedexception e) { $ e.printstacktrace (); -         } -TMP-=amount; theBalance =tmp; -     }Wuyi}
View Code

Implement an ATM simulation class bank. It uses the Subtractamount () method to deduct the balance of the account. This class implements the Runnable interface to execute as a thread.

1  Public class Implements runnable{2 }

For this class, add the Account object and initialize the object with the constructor.

1 Private Account account ; 2 3  Public Bank Account {4     this. account = account ; 5 }

Implement the Run () method. It will call the Subtranctamount () method to deduct the balance of the account and perform the loop 100 times.

1  Public void Run () 2 {3      for (int i = 0; i < i++) {4         account.subtranctamount (+); 5     }67}  8         

Implement company simulation. It uses Addamount () to recharge the balance of the account. This class implements the Runnable interface to run as a thread.

1 public class company implements Runnable {}

For the company class, add the Account object, initialize the object with the constructor.

1 Private Account account ; 2 3  Public Company (account) {4     this. account = account ; 5 }

Implement the Run () method. It will call the Addamount () method to recharge the balance of the account and loop through the execution 100 times.

1  Public void Run () 2 {3      for (int i = 0; i < i++) {4         account.addamount (+); 5     }6 }

Sample Main Program

1  Public Static voidMain (string[] args)throwsinterruptedexception2     {3         //create account class initial value4Account account=NewAccount ();5Account.setbalance (1000);6         7         //Create a company class8Company Company=NewCompany (account);9Thread companythread=NewThread (company);Ten          One         //Create an ATM simulation class ABank bank=NewBank (account); -Thread bankthread=NewThread (bank); -  the         //Show initial balances -System.out.println ("Account:initial Balance:" +account.getbalance ()); -          -         //Start Two threads + Companythread.start (); - Bankthread.start (); +          A         //use Join () to wait for thread to run complete at Companythread.join (); - Bankthread.join (); -          -         //Show Final Results -System.out.println ("Account:final Balance:" +account.getbalance ()); -}

In this case, by using TMP to temporarily store the account balance, a false scenario has been created: This temporary variable takes the balance first, then accumulates the amount, and then updates the final result to the account balance. In addition, the sleep () method has been used in the case to increase the delay so that the thread that is executing this method sleeps 10ms, while other threads may also execute the method, which may change the balance and throw an error. The synchroniized keyword mechanism avoids the occurrence of such errors.

Let's first remove the Addamount () and Subtractamount () method's synchroniized keywords to see the results of the operation:

  

If you run this program multiple times, there will be different results. Because the JVM does not guarantee the order in which threads are executed.

Add the Synchroniized keyword to the running result:

  

The use of the Synchroniized keyword guarantees the correct access to the shared data in the concurrent program.

The method of an object is declared with the Synchroniized keyword and can only be accessed by one thread. If thread A is executing a synchronous method Syncmethoda (), thread B will execute another synchronization method Syncmethodb () for this object, and thread B is blocked until thread a accesses the end. However, if thread B accesses a different object of this class, then two threads are not blocked.

More information

The Synchroniized keyword reduces the performance of the system, so it can only be used on methods that require modification of shared data in a concurrency scenario.

Methods that are declared by the Synchroniized keyword can be called using recursion. When a thread accesses a synchronous method of an object, it can also invoke other synchronization methods of the object, as well as the method being executed, without having to obtain the right to use the method again.

We can protect the access to the code block by synchroniized the keyword. Access to the critical section should be as short as possible.

Multithreading (one) 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.