【发布时间】:2016-09-30 14:46:26
【问题描述】:
这是我的以下代码:
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Start"+" "+Thread.currentThread().getName());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("End!"+" "+Thread.currentThread().getName());
}
}
});
executor.shutdown();
executor.awaitTermination(1, TimeUnit.SECONDS);
这是我的输出:
Start pool-1-thread-1
End! pool-1-thread-1
Start pool-1-thread-1
End! pool-1-thread-1
Start pool-1-thread-1
End! pool-1-thread-1
Start pool-1-thread-1
End! pool-1-thread-1
Start pool-1-thread-1
End! pool-1-thread-1
我的理解是,在我的代码中,FixedThreadPool 中有 5 线程。所以当我运行我的代码时,它应该输出所有5 线程,对吧?还是我误会了什么?
在我的输出中thread-1 每次都开始和结束,但是当它在for 循环中循环时,它不应该输出所有5 线程吗?
因为如果只有 1thread 正在执行 task 那么我们为什么还需要 5 threads?
有什么办法可以让所有5线程在控制台上输出吗?(我是新手)
【问题讨论】:
-
您已提交一项任务。为什么你希望它在 5 个线程上运行?
-
我是新手,是的,我现在知道了。谢谢。
标签: java multithreading threadpool