线程A加1,线程B减1,为什么a都是输出0?

 * 存在实例变量a=0
 * 线程A对a加1
 * 线程B对a减1
 * 
 * 求最终a的值

 */


为什么没有出现输出1   0之类的结果。比如线程A先判断,然后加1并输出a=1,线程B后判断(此时a=1),对a减1,输出a=0。

然后可不可以是 1   -1

<br>



```/*
 * 存在实例变量a=0
 * 线程A对a加1
 * 线程B对a减1
 * 
 * 求最终a的值

 */

class ThreadCalculate implements Runnable {
    private int a = 0;

    @Override
    public void run() {
        method1();
    }


    public void method1() {
        if (Thread.currentThread().getName().equals("A")) {
            a += 1;

        } else if (Thread.currentThread().getName().equals("B")) {

            a -= 1;

        } else {
            System.out.println(Thread.currentThread().getName());
        }

        System.out.println("最终 a=" + a);
    }

}

public class 线程同步案例 {

    public static void main(String[] args) {
        ThreadCalculate calculate = new ThreadCalculate();
        Thread t1 = new Thread(calculate, "A");
        Thread t2 = new Thread(calculate, "B");
        t1.start();
        t2.start();
    }

}

输出结果:
最终 a=0
最终 a=0

https://www.cnblogs.com/qfxydtk/p/8728877.html

你用同个calculate,那么操作的a是通个对象,线程又是异步同时跑的,当执行到输出语句的时候,另一边的加或减一定执行完了,所以输出都是0

ThreadCalculate calculate1 = new ThreadCalculate();
ThreadCalculate calculate2 = new ThreadCalculate();
Thread t1 = new Thread(calculate1, "A");
Thread t2 = new Thread(calculate2, "B");
t1.start();
t2.start();