newFixedThreadPool
创建一个固定大小的线程池。
shutdown():用于关闭启动线程,如果不调用该语句,jvm不会关闭。
awaitTermination():用于等待子线程结束,再继续执行下面的代码。该例中我设置一直等着子线程结束。
public class Test { public static void main(String[] args) throws IOException, InterruptedException { ExecutorService service = Executors.newFixedThreadPool( 2 ); for ( int i = 0 ; i < 4 ; i++) { Runnable run = new Runnable() { @Override public void run() { System.out.println( "thread start" ); } }; service.execute(run); } service.shutdown(); service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); System.out.println( "all thread complete" ); } }
public class Test { public static void main(String[] args) throws IOException, InterruptedException { ExecutorService service = Executors.newFixedThreadPool(2 ); for ( int i = 0 ; i < 4 ; i++) { Runnable run = new Runnable() { @Override public void run() { System.out.println("thread start" ); } }; service.execute(run); } service.shutdown(); service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); System.out.println("all thread complete" ); } }
输出:
thread start
thread start
thread start
thread start
all thread complete