Multi-thread synchronization in Java Development

Source: Internet
Author: User
When writing a class, if the code in this class may run in a multi-threaded environment, you should consider the synchronization issue. Synchronized, a language-level synchronization primitive, is built in Java, which greatly simplifies the use of multi-thread synchronization in Java.

First, we will write a very simple multi-thread program that simulates multiple threads in the bank to simultaneously perform deposit and withdrawal operations on the same savings account.

In the program, we use a simplified account class that represents the information of a bank account. In the main program, we first generate 1000 threads, and then start them. Every thread stores 100 yuan for John's account, and then immediately retrieves 100 yuan. In this way, for John's account, the final account balance should be 1000 yuan. However, the running result is beyond our imagination. First, let's take a look at our demo code:

Class account
{
String name; float amount;
Public Account (string name, float amount)
{
This. Name = Name;
This. Amount = amount;
}
 
Public void deposit (float AMT)
{
Float TMP = amount;
TMP + = AMT;
Try
{
Thread. Sleep (100 );
// Simulate the time required for other processing, such as refreshing the database.
}
Catch (interruptedexception E)
{
// Ignore
}
Amount = TMP;
}

Public void withdraw (float AMT)
{
Float TMP = amount;
TMP-= AMT;
Try
{
Thread. Sleep (100 );
// Simulate the time required for other processing, such as refreshing the database.
}
Catch (interruptedexception E)
{
// Ignore
}
Amount = TMP;
}

Public float getbalance ()
{
Return amount;
}
}

Public class accounttest
{
Private Static int num_of_threads = 1000;
Static thread [] threads = new thread [num_of_thread];
Public static void main (string [] ARGs)
{
Final Account ACC = new account ("John", 1000.0f );
For (INT I = 0; I <num_of_thread; I ++)
{
Threads [I] = new thread (New runnable ()
{
Public void run ()
{
ACC. Deposit (100366f );
ACC. Withdraw (100366f );
}
}
);
Threads [I]. Start ();
}
For (INT I = 0; I <num_of_thread; I ++)
{
Try {threads [I]. Join ();
// Wait until all threads finish running
}
Catch (interruptedexception E)
{
// Ignore
}
}
System. Out. println ("Finally, John's balance is:" + acc. getbalance ());}}

Note: In the deposit and withdraw methods of the account, the reason why we need to use a temporary variable for the amount operation is first stored, sleep for a period of time, and then assign the value to amount, it is used to simulate actual running conditions. In real systems, account information must be stored in persistent media. For example, in RDBMS, the sleep time here is equivalent to time-consuming database operations, finally, assigning the value of the Temporary Variable TMP to amount is equivalent to writing the amount changes to the database. Run accounttest. The result is as follows (each result is different ):

E:/Java/exer/bin> JAVA accounttest
Finally, John's balance is: 3900.0

E:/Java/exer/bin> JAVA accounttest
Finally, John's balance is: 4900.0

E:/Java/exer/bin> JAVA accounttest
Finally, John's balance is: 4700.0

E:/Java/exer/bin> JAVA accounttest
Finally, John's balance is: 3900.0

E:/Java/exer/bin> JAVA accounttest
Finally, John's balance is: 3900.0

E:/Java/exer/bin> JAVA accounttest
Finally, John's balance is: 5200.0

Why is this problem? This is the problem of synchronization in multiple threads. In our program, the amount in the account will be accessed by multiple threads at the same time. This is a competitive resource, usually called a race condition. For resources shared by multiple threads, We must synchronize the resources to prevent modifications of one thread from being overwritten by another thread. In our program, the amount in the account is a race condition, so all the modifications to the amount must be synchronized. We will synchronize the deposit () and withdraw () methods, to:

Public synchronized void deposit (float AMT)
{
Float TMP = amount;
TMP + = AMT;
Try
{
Thread. Sleep (1 );
// Simulate the time required for other processing, such as refreshing the database.
}
Catch (interruptedexception E)
{
// Ignore
}
Amount = TMP;
}

Public synchronized void withdraw (float AMT)
{
Float TMP = amount;
TMP-= AMT;
Try
{
Thread. Sleep (1 );
// Simulate the time required for other processing, such as refreshing the database.
}
Catch (interruptedexception E)
{// Ignore}
Amount = TMP;
}

Then run the command again to get the correct result. The getbalance () in the account also accesses amount. Why is it not synchronized with getbalance? Because getbalance () does not modify the value of amount, access to it by multiple threads at the same time will not cause data confusion.

 

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.