Don't overturn it, the use of member variables and local variables in multi-threading, it is enough to read this article

1. The difference between member variables and local variables

  1. Different positions in the class
    Member variables : outside the method in the class
    Local variables : in the method or code block, or on the declaration of the method (that is, in the parameter list)
  2. Different locations in memory
    Member variables : In the heap (static area in the method area), member variables belong to objects, and objects are stored in the heap
    Local variables : In the stack, local variables belong to methods, and methods are stored in stack memory
  3. Different life cycle
    member variables : exist with the creation of the object, disappear with the disappearance of the object
    local variables : exist with the call of the method or the execution of the code block, and disappear with the completion of the method call or the execution of the code block disappear
  4. Initial value
    member variable : with default initial value
    Local variable : no default initial value, must be assigned before use
  5. Note:
    The problem of duplicate names between member variables and local variables is based on the principle of proximity;
    you can use the this keyword to distinguish, this.string refers to the member variables in the class, not inside the method.

Code example:

public class test {
    
    
    public static void main(String[] args) {
    
    
        int a = 3;          // 这个是成员变量
        Thread thread = new Thread(() -> {
    
    
            int b = 4;      // 这是一个局部变量
        });
        thread.start();
    }
}

2. Modify call member variables in multithreading


When two or more threads access the member variables of the object, because the member variables belong to the object, the two threads share a member variable, that is, when a thread changes the value of the member variable, it is have an effect on other threads.

If you must use a member variable, you can set the variable to a static static value or an AtomicInteger atomic value, but this will cause confusion. Take the static type as an example:

public class test {
    
    
    static int i = 0;
    public static void main(String[] args) throws Exception {
    
    
        Thread thread1 = new Thread(() -> {
    
    
            for (i = 0; i < 50; i++) {
    
    
                System.out.print(i + " ");
            }
        });
        thread1.start();

        Thread thread2 = new Thread(() -> {
    
    
            for (i = 0; i < 50; i++) {
    
    
                System.out.print(i + " ");
            }
        });
        thread2.start();
    }
}

输出:
0 1 2 3 4 5 6 1 1 3 4 5 6 7 2 8 10 11 12 13 14 15 9 17 18 19 16 20 22
23 21 25 26 27 28 29 30 31 32 33 34 35 36 24 38 39 40 41 42 43 44 45 
46 37 48 49 47

We found that the number 0-50 should have been output twice, but the resulting output was garbled characters, which also verified our point of view: in multi-threading, calling and modifying member variables by a thread will affect other threads.

Of course, if we only call member variables and do not modify them, it is possible. code show as below:

public class test {
    
    
    public static void main(String[] args) throws Exception {
    
    
        int i = 50;
        Thread thread1 = new Thread(() -> {
    
    
            for (int i1 = 0; i1 < i; i1++) {
    
    
                System.out.print(i1 + " ");
            }
        });
        thread1.start();

        Thread thread2 = new Thread(() -> {
    
    
            for (int i1 = 0; i1 < i; i1++) {
    
    
                System.out.print(i1 + " ");
            }
        });
        thread2.start();
    }
}

输出:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 0 17 18 1 2 3 4 5 6 7 8 9 10
11 19 12 13 14 15 16 17 18 19 20 20 21 22 23 24 25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 

It can be seen that the out-of-order array of 0-50 will be output twice, which is feasible.

Is there any way to call and modify member variables without being affected by other threads?


We can assign multiple member variables and change them to static type or AtoimcInteger type. In this way, multiple member variables will be stored in different addresses. Next, each thread can call a different member variable. Take the member variable of type AtomicInteger as an example, the code is as follows:

public class test {
    
    
    public static void main(String[] args) throws Exception {
    
    
        int i = 50;

        AtomicInteger i1 = new AtomicInteger(i);
        Thread thread1 = new Thread(() -> {
    
    
            for (i1.set(0); i1.get() < 50; i1.getAndIncrement()) {
    
    
                System.out.print(i1 + " ");
            }
        });
        thread1.start();

        AtomicInteger i2 = new AtomicInteger(i);
        Thread thread2 = new Thread(() -> {
    
    
            for (i2.set(0); i2.get() < 50; i2.getAndIncrement()) {
    
    
                System.out.print(i2 + " ");
            }
        });
        thread2.start();
    }
}

结果:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 16 1 2 17 18 3 4 19 20 5 6 7 8
9 10 11 12 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 13 37 38 39 
14 15 16 17 18 19 40 20 41 21 22 23 24 25 26 27 28 29 42 30 31 43 44 45 
46 47 48 32 33 34 49 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 

It can be seen that the out-of-order array of 0-50 will be output twice, which is feasible.

Therefore, it can be concluded that if we want to call and modify member variables in a multi-threaded environment, we need to make multiple copies of the member variables and change them to static type or AtoimcInteger type, just call.

3. Modify and call local variables in multithreading


Since each local variable is private to each thread, it can be modified directly without affecting other threads. code show as below:

public class test {
    
    
    public static void main(String[] args) throws Exception {
    
    
        Thread thread1 = new Thread(() -> {
    
    
            int i = 0;
            for (i = 0; i < 50; i++) {
    
    
                System.out.println(i + " ");
            }
        });
        thread1.start();

        Thread thread2 = new Thread(() -> {
    
    
            int i = 0;
            for (i = 0; i < 50; i++) {
    
    
                System.out.println(i + " ");
            }
        });
        thread2.start();
    }
}

输出:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 0 1 2 3 4 5 
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 
31 32 33 34 35 36 37 38 39 40 41 42 43 23 44 24 25 45 46 47 26 48 49 27 
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 

It can be seen that the out-of-order array of 0-50 will be output twice, which is feasible.

Guess you like

Origin blog.csdn.net/weixin_43899069/article/details/121973745