public static void main(String[] args) {
ScheduledExecutorService service = Executors.newScheduledThreadPool(2);
System.out.println("begin");
for (int a = 0; a < 10; a++) {
System.out.println(a);
final int count = a;
service.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+": "+count);
}
}, 2,2, TimeUnit.SECONDS);
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} service.shutdown();
System.out.println("stop");
}运行结果:
begin
0
1
2
3
4
5
6
7
8
9
pool-1-thread-1: 0
pool-1-thread-2: 1
pool-1-thread-1: 2
pool-1-thread-2: 3
pool-1-thread-1: 4
pool-1-thread-2: 5
pool-1-thread-1: 6
pool-1-thread-2: 7
pool-1-thread-1: 8
pool-1-thread-2: 9
pool-1-thread-1: 0
pool-1-thread-2: 1
pool-1-thread-1: 2
pool-1-thread-2: 3
pool-1-thread-1: 4
pool-1-thread-2: 5
pool-1-thread-1: 6
pool-1-thread-2: 7
pool-1-thread-1: 8
pool-1-thread-2: 9
stop
为什么线程内部print了 0-9两次循环?
为什么a只打印一次循环?
ScheduledExecutorService service = Executors.newScheduledThreadPool(2);
System.out.println("begin");
for (int a = 0; a < 10; a++) {
System.out.println(a);
final int count = a;
service.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+": "+count);
}
}, 2,2, TimeUnit.SECONDS);
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} service.shutdown();
System.out.println("stop");
}运行结果:
begin
0
1
2
3
4
5
6
7
8
9
pool-1-thread-1: 0
pool-1-thread-2: 1
pool-1-thread-1: 2
pool-1-thread-2: 3
pool-1-thread-1: 4
pool-1-thread-2: 5
pool-1-thread-1: 6
pool-1-thread-2: 7
pool-1-thread-1: 8
pool-1-thread-2: 9
pool-1-thread-1: 0
pool-1-thread-2: 1
pool-1-thread-1: 2
pool-1-thread-2: 3
pool-1-thread-1: 4
pool-1-thread-2: 5
pool-1-thread-1: 6
pool-1-thread-2: 7
pool-1-thread-1: 8
pool-1-thread-2: 9
stop
为什么线程内部print了 0-9两次循环?
为什么a只打印一次循环?
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货