多线程中,static函数与非static函数的区别?

最近在学习多线程,刚入门,好多东西不懂,下面这段代码今天想了半天也没明白,希望看到的兄弟姐妹能解释下。

public class NotThreadSafeCounter extends Thread {
    
    private static int counter = 0;
    
    public void run() {
        System.out.println("counter:" + getCount());
    }
    public static int getCount() {
        
        try {
            Thread.sleep(1500);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return counter++;
        
    }
    
    public static void main(String[] args) {
        
        for (int i = 0; i < 5; i++) {
            new NotThreadSafeCounter().start();
        }
    }
    
}
View Code

下面是输出结果(当然了,输出结果不确定)

counter:1
counter:0
counter:2
counter:3
counter:4

不明白的地方是为什么0至4全部输出,这种情况下有没有可能五个thread中的某几个读到了相同的值。如果去掉static,就会出现0-4不全输出的结果,希望帮忙解释下。

原文地址:https://www.cnblogs.com/RobertC/p/3601225.html