Executors.newFixedThreadPool(2);开启一个有限的线程池
service.shutdown();是在所有线程提交给executors内部的队列后就执行。
此时,线程必定提交,但未必开始执行,未必执行完成。
package test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyExecutor extends Thread {
private int index;
public MyExecutor(int i){
this.index=i;
}
public void run(){
try{
long time=System.currentTimeMillis();
System.out.println("["+this.index+"] start.");
Thread.sleep((int)(Math.random()*1000));
System.out.println("["+this.index+"]"+(System.currentTimeMillis()-time)+" end.");
}
catch(Exception e){
e.printStackTrace();
}
}
public static void main(String args[]){
ExecutorService service=Executors.newFixedThreadPool(2);
for(int i=0;i<10;i++){
service.execute(new MyExecutor(i));
System.out.println("["+i+"] into queue");
//service.submit(new MyExecutor(i));
}
service.shutdown();
System.out.println("submit finish");
}
}
package test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyExecutor extends Thread {
private int index;
public MyExecutor(int i){
this.index=i;
}
public void run(){
try{
long time=System.currentTimeMillis();
System.out.println("["+this.index+"] start.");
Thread.sleep((int)(Math.random()*1000));
System.out.println("["+this.index+"]"+(System.currentTimeMillis()-time)+" end.");
}
catch(Exception e){
e.printStackTrace();
}
}
public static void main(String args[]){
ExecutorService service=Executors.newFixedThreadPool(2);
for(int i=0;i<10;i++){
service.execute(new MyExecutor(i));
System.out.println("["+i+"] into queue");
//service.submit(new MyExecutor(i));
}
service.shutdown();
System.out.println("submit finish");
}
}