代码:
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 |
答案 0 :(得分:1)
ScheduledExecutorService使用分配的线程以指定的速率运行提交的任务。误解是每个线程与1个任务相关联,仅用于以指定的频率运行该特定任务。但事实并非如此,所以这是有道理的。