的Java ScheduledExecutorService的给奇怪的结果
问题描述:
代码:的Java ScheduledExecutorService的给奇怪的结果
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Test implements Runnable {
private Integer xyz = 1;
public static void main(String[] args) throws InterruptedException {
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
Test test = new Test();
test.xyz = 20;
Test test2 = new Test();
System.out.println("Values of xyz = " + test.xyz + " , " + test2.xyz);
executorService.scheduleWithFixedDelay(test, 100, 1000, TimeUnit.MILLISECONDS);
executorService.scheduleWithFixedDelay(test2, 100, 100, TimeUnit.MILLISECONDS);
executorService.awaitTermination(3000, TimeUnit.MILLISECONDS);
executorService.shutdown();
}
@Override
public void run() {
this.xyz += (int) Thread.currentThread().getId();
System.out.println(Thread.currentThread().getId() + " " + this.xyz);
}
}
输出:
Values of xyz =
20 1 |
10 30 |
11 12 |
11 23 |
11 34 |
11 45 |
11 56 |
11 67 |
11 78 |
11 89 |
11 100 |
11 111 |
10 40 |
11 122 |
11 133 |
11 144 |
11 155 |
11 166 |
11 177 |
11 188 |
11 199 |
11 210 |
11 221 |
10 50 |
11 232 |
11 243 |
11 254 |
11 265 |
10 275 | (10 should have been 60 here)
10 285 |
10 295 |
10 305 |
10 315 |
答
ScheduledExecutorService的使用分配给运行在指定的速度提交的任务线程。误解是每个线程都与1个任务相关联,仅用于以指定的频率运行该特定任务。但事实并非如此,所以这是有道理的。
'test'运行3次,'test2'在2个不同的线程上执行。那里没有什么令人惊讶的。你为什么期望60? – assylias
我错过了一些关于ScheduledExecutorService的上下文,我想不。的任务等于没有。 threadPool大小。不知道他们是在多个线程中执行以满足费率要求。 - 谢谢 –