代码之家  ›  专栏  ›  技术社区  ›  Faraz

全局变量值在可运行实现中是线程安全的?

  •  0
  • Faraz  · 技术社区  · 5 年前

    public class MyRunnable implements Runnable {
    
    private String taskName;
    
    private int executeCount = new Random().nextInt(10);
    
    public MyRunnable(String taskName) {
        this.taskName = taskName;
    }
    
    @Override
    public void run() {
        System.out.println(this.taskName + " in Thread ID: " + Thread.currentThread().getId() + ". execute count: " + ++executeCount);
    }
    }
    

    我从10个线程开始并发运行代码。不知何故 executeCount 保持安全,我看到了预期值。

    这是暂时的吗?每次我运行测试,它只是碰巧打印正确的值,但实际上它是不安全的?或者行为是预期的?

    这是我的出发点:

    @SpringBootApplication
    @EnableScheduling
    public class DynamicSchedularApplication implements ApplicationRunner {
    
    public static void main(String[] args) {
        SpringApplication.run(DynamicSchedularApplication.class, args);
    }
    
    @Override
    public void run(ApplicationArguments args) throws Exception {
        ThreadPoolTaskScheduler ts = threadPoolTaskScheduler();
        for (int i = 0; i < 10; i++) {
            ts.scheduleAtFixedRate(new MyRunnable("Task"+i),
                Duration.ofMillis(3000));
        }
    }
    
    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        ThreadPoolTaskScheduler ts = new ThreadPoolTaskScheduler();
        ts.setPoolSize(10);
        return ts;
    }
    
    }
    
    0 回复  |  直到 5 年前
        1
  •  1
  •   akuzminykh    5 年前

    因为每根线都有它自己的 executeCount 它是非静态的,每个线程只访问自己的线程 执行计数 Runnable ,重要的是变量的范围以及从何处访问它。