多线程操作共享变量

public class TestJava {

    public static void main(String[] args) {

        A a = new A();
        for (int i = 0; i < 3; i++) {
            T t = new T(a);
            t.start();
        }

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(a.getNum());

    }

}

class A {

    int num = 0;

    public void test() {
        for (int i = 0; i < 100000; i++) {
            num++;
        }
    }

    public int getNum() {
        return num;
    }

}

class T extends Thread {
    private A a;

    public T(A a) {
        this.a = a;
    }

    @Override
    public void run() {
        a.test();
    }
}

解决方案: Synchronized, Lock, AtomicInteger

你可能感兴趣的:(多线程操作共享变量)