我试图执行 5 个线程同时完美启动。但看下面的输出,我认为它们是同时开始的,但不是同时开始的,因为年龄计数器总是以 5 计数结束。如果他们同时执行 这群人的年龄输出必须相同。通过真正的并发或完美的同时,我认为所有 5 个线程将 1 作为年龄传递,并且所有线程打印相同的年龄而不是递增值。请纠正我。
public class ExecutorServiceTester {
public static void main(String args[]) throws InterruptedException {
ExecutorServiceTester tester = new ExecutorServiceTester();
tester.executeTester();
}
private void executeTester() throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(10);
Runnable worker = new MyRunnable(1);
for (int i = 0; i < 10; i++) {
executorService.execute(worker);
} executorService.shutdown();
}
public static class MyRunnable implements Runnable {
int age = 0;
public MyRunnable(int count) {
this.age = count;
}
@Override
public void run() {
System.out.println(new Timestamp(new Date().getTime())+" ThreadName:"+Thread.currentThread().getName()
+ " Age " + age++);
}
} }
输出:
2015-03-23 02:02:18.243 ThreadName:pool-1-thread-1 Age 1
2015-03-23 02:02:18.243 ThreadName:pool-1-thread-5 Age 3
2015-03-23 02:02:18.243 ThreadName:pool-1-thread-3 Age 5
2015-03-23 02:02:18.243 ThreadName:pool-1-thread-2 Age 2
2015-03-23 02:02:18.243 ThreadName:pool-1-thread-4 Age 4
尝试使用 Executors.newCachedThreadPool();并将数量增加到 12,然后输出有一些有趣的东西
2015-03-23 02:17:57.189 **ThreadName:pool-1-thread-4 Age 1**
2015-03-23 02:17:57.189 ThreadName:pool-1-thread-10 Age 3
2015-03-23 02:17:57.189 ThreadName:pool-1-thread-12 Age 2
2015-03-23 02:17:57.189 **ThreadName:pool-1-thread-11 Age 1** ...
最佳答案
所有线程使用相同计数器的原因是您向它们提供相同的 Runnable 实例。只需为循环内的每个线程创建一个新线程即可:
for (int i = 0; i < 10; i++) {
Runnable worker = new MyRunnable(1);
executorService.execute(worker);
}
关于java - 程序如何保证使用执行器框架同时执行多个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29199374/