创建一3个线程的线程池,为其分配5个任务,预期结果应该是:三个线程先为0、1、2号任务服务,完成后再有两个线程为其余两个任务服务。可是运行结果确不是这样,程序如下:
package thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ExecutorService executorService = Executors.newFixedThreadPool(3);
for (int i = 0; i < 5; i++) {
final int task = i;
executorService.execute(new Runnable() {
@Override
public void run() {
for (int j = 0; j < 5; j++) {
/*try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
System.out.println(Thread.currentThread().getName()
+ " is running loop of " + j + " of task "
+ task);
}
}
});
}
System.out.println("5 task has put in!");
executorService.shutdown();
}
}
后来加上被注释的那几行,在运行结果才跟预期的一样!现在我不明白为什么要休眠20毫秒,请高手给解释一下!谢谢! |
|