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 count variable:
  1. //线程不安全的类

  2. public class UnsafeCount {

  3.     private int count = 0;    //该变量是共享的

  4.     public void increase() {    //这里没有同步机制,多个线程可以同时访问

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

  6.     }

  7.     public int getCount() {

  8.         return count;

  9.     } 

There are 3 ways to fix this problem:

1. Do not share the state variable in the thread, you can encapsulate the variable into the method (the stateless object must be thread safe), because the variables in the method are exclusive to each thread and are not shared with other threads. Like what:
    1. public int add(int count){

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

    3. }

2. Modify the state variable to a variable that is immutable.
    1. private final  int count = 0;

3. Use the synchronization policy in the Access state variable.
    1. public synchronized  void increase() {

    2. count++;

    3. }

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.