这是我的以下代码:
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
我的理解是,在我的代码中,5
中有FixedThreadPool
个5
个主题。因此,当我运行我的代码时,它应该输出所有thread-1
个线程,对吧?或者我误解了什么?
在我的输出5
中每次都开始和结束,但是当它在for
循环中循环时,它是否应该输出所有thread
个线程?
如果task
只有1 threads
,那么为什么我们甚至需要5 5
?
有没有办法在控制台上输出所有select coalesce(jan.field, feb.field, mar.field, ... dec.field, 0) as result
from atable a
left join jan on a.id = jan.id and a.month = 'jan'
left join feb on a.id = jan.id and a.month = 'feb'
left join mar on a.id = jan.id and a.month = 'mar'
-- ...
left join dec on a.id = jan.id and a.month = 'dec'
个线程?(我是新手)
答案 0 :(得分:2)
您只发布一个Runnable
,因此ExecutorService
运行一项任务。它只使用一个线程。要使用多个主题,您必须多次致电submit
,或者使用invokeAll
可运行的内容致电Collection
。
<强> 修改 强>
这样的事情:
public void test() {
int numberOfThreads = 5;
ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
for(int i=0; i<numberOfThreads; i++){
executorService.submit(createRunnable());
}
}
private Runnable createRunnable() {
return new Runnable() {
@Override
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());
}
}
};
}