zoukankan      html  css  js  c++  java
  • 多线程中,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不全输出的结果,希望帮忙解释下。

  • 相关阅读:
    linux 杂类
    set
    C++ 基础 杂类
    linux 添加samba账户
    git 常用命令
    git 设置bitbucket 邮箱、用户
    C++ shared_ptr
    git 免密码配置
    2014的新目标
    为/Date(1332919782070)/转时间2013-09-23
  • 原文地址:https://www.cnblogs.com/RobertC/p/3601225.html
Copyright © 2011-2022 走看看