Variable of multi-threaded concurrent programming

Source: Internet
Author: User

What you need to be interested in writing thread safety:
    • Shared variables

    • Variable variable

sharing means that multiple threads can be accessed at the same time, and mutable means that their values can change over the life cycle. For example, the following countvariables:
  
 

    //线程不安全的类

    public class UnsafeCount {

    private int = 0 //the variable is a shared

    public   void () {

            count++;    //该变量是可变的

        }

    public   int () {

            return count;

        } 


There are 3 ways to fix this problem:
1. You can encapsulate a variable in a method without sharing the state variable in the thread (Stateless objects must be thread-safe)because the variables in the method are exclusive to each thread and are not shared with other threads. For example:
  
 

    public    add ( >int

    return ++count;//这里也可以说无状态的对象一定是线程安全的

    }

2.Modify the state variable to a variable that is immutable.
  
 

      private final  int count = 0;

3. Use the synchronization policy in the Access state variable.
  
 

    public   void () {

    count++;

    }




From for notes (Wiz)

Variable of multi-threaded concurrent programming

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.