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;
}
}