62,620
社区成员
发帖
与我相关
我的任务
分享
package test;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ESShutdownTest {
private static ExecutorService ES=Executors.newFixedThreadPool(10);
public static void main(String[] args) {
//监视console输入,如果输入CLOSE,则执行ES的shutdown方法
Thread scanner =new Thread(new ScanerThread());
scanner.start();
for(int i=0;i<100;i++){
Thread t=new Thread(new RunThread());
ES.submit(t);
}
ES.shutdown();
}
/**
* 模拟工作
* @author Administrator
*
*/
private static class RunThread implements Runnable {
public void run() {
try {
System.out.println(Thread.currentThread().getName()+":begin");
Thread.sleep(10000);
System.out.println(Thread.currentThread().getName()+":finish!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static class ScanerThread implements Runnable {
public void run() {
System.out.println("Scanner is running");
Scanner in=new Scanner(System.in);
String key=in.nextLine();
System.out.println(key);
if(key.equals("CLOSE")){
System.out.println("ThreadPool will close!");
ES.shutdown();
try {
boolean b=ES.awaitTermination(10, TimeUnit.SECONDS);
System.out.println(b);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else if(key.equals("CLOSE NOW")){
System.out.println("ThreadPool will close NOW !");
ES.shutdownNow();
}
}
}
}