Example to explain the variable _java of Java concurrent programming

Source: Internet
Author: User

To write thread safety concerns:

1. Shared variables
2. Variable variables

Sharing means that multiple threads can access at the same time, and variability means that their values can be changed in the lifecycle.
For example, the following count variables:

Copy Code code as follows:

Thread-Unsafe classes
public class Unsafecount {
private int count = 0; The variable is shared
public void Increase () {//There is no synchronization mechanism, multiple threads can access both
count++; The variable is variable
}
public int GetCount () {
return count;
}
}

There are 4 different ways to fix this problem:

1. The state variable is not shared in the thread, and the variable can be encapsulated into the method (the stateless object must be thread-safe) because the variable in the method is exclusive to each thread and is not shared with other threads. Like what:

Copy Code code as follows:

public int Add (int count) {
Return ++count;//This can also be said that stateless objects must be thread-safe
}

2. Modify the state variable to an immutable variable.
Copy Code code as follows:

Private final int count = 0;

3. Use the synchronization policy in the Access state variable.
Copy Code code as follows:

Public synchronized void Increase () {
count++;
}

4. Use atomic variable classes.
Copy Code code as follows:

Private Atomicinteger count;
public void Increase () {
Count.getandadd (1);
}

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.