Java multithreaded thread synchronization problem

Source: Internet
Author: User

Thread synchronization
In the multi-threaded programming environment, it may look at the code that is not the problem after thousands of tens or more times, there are some looking at the strange problem, the reason is that there may be two or more threads into the same piece of business processing code to cause the judgment to fail. To solve this problem, Java introduced a synchronization monitor to solve this problem. The common way to synchronize a monitor is to synchronize the code block, which is to add a synchronous lock to a piece of code.

Package CN.TEST.HF;

Import Java.math.BigDecimal;

/**
* Simulated money-taking operation
*/
public class Runnabletest implements Runnable {

Private account Account;

The current user wants to withdraw money
Private BigDecimal withdrawal;

Public Runnabletest (account account, BigDecimal withdrawal) {

This.account = account;
This.withdrawal = withdrawal;
}

public void Run () {


Determine if the current user is taking more than the remaining amount of money
if (This.withdrawal.subtract (This.account.getHaveMoney ()). Doublevalue () <= 0) {

Reduce the balance of the account after the money is taken
This.account.setHaveMoney (This.account.getHaveMoney (). Subtract (This.withdrawal));
System.out.println ("Current User" + Thread.CurrentThread (). GetName () + "Withdraw Amount" + This.withdrawal + ", withdraw successfully! ");
} else {

System.out.println ("Current User" + Thread.CurrentThread (). GetName () + "amount Taken" + This.withdrawal + "exceeded limit! ");
}
}

public static void Main (string[] args) {

try {

Account Account = new account ();

Account.sethavemoney (New BigDecimal (1000));
Account.setremainmoney (New BigDecimal (1000));

Runnabletest r1 = new Runnabletest (account, New BigDecimal ("800"));
runnabletest r2 = new Runnabletest (account, New BigDecimal ("900"));

thread T1 = new Thread (r1, "Zhang San");
T1.start ();
Thread t2 = new Thread (R2, "John Doe");
T2.start ();
Restore after completion
} catch (Exception e) {


}
}
}

In the case of high concurrency, Zhang San and Li Shicao make the same account, the problem may be that Zhang San and John Doe are successful, then the balance of the account is negative.

Deal with this problem

Method 1, use synchronized (obj) to synchronize the code block to lock the current obj object, obj is the synchronization monitor, at any time only one thread can obtain a lock on the synchronization monitor, after the thread operation to release the object lock.

The code is as follows:
public void Run () {

Synchronized (This.account) {
Determine if the current user is taking more than the remaining amount of money
if (This.withdrawal.subtract (This.account.getHaveMoney ()). Doublevalue () <= 0) {

Reduce the balance of the account after the money is taken
This.account.setHaveMoney (This.account.getHaveMoney (). Subtract (This.withdrawal));
System.out.println ("Current User" + Thread.CurrentThread (). GetName () + "Withdraw Amount" + This.withdrawal + ", withdraw successfully! ");
} else {

System.out.println ("Current User" + Thread.CurrentThread (). GetName () + "amount Taken" + This.withdrawal + "exceeded limit! ");
}
}
}

Method two, using synchronous method, synchronous method and synchronous code block corresponding, synchronous method is to use synchronized to decorate a method, for synchronized modified instance method does not need to display the specified synchronization controller, synchronous method synchronization monitor is the current object, that is this, Immutable classes are always thread-safe, mutable classes are not thread-safe, so the corresponding set methods can be modified by synchronized to control multi-threaded concurrent access.

Java multithreaded thread synchronization problem

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.