ExecutorService的正确关闭方法
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(5);
final long waitTime = 8 * 1000;
final long awaitTime = 5 * 1000;
Runnable task1 = new Runnable(){
public void run(){
try {
System.out.println("task1 start");
Thread.sleep(waitTime);
System.out.println("task1 end");
} catch (InterruptedException e) {
System.out.println("task1 interrupted: " + e);
}
}
};
Runnable task2 = new Runnable(){
public void run(){
try {
System.out.println(" task2 start");
Thread.sleep(1000);
System.out.println(" task2 end");
} catch (InterruptedException e) {
System.out.println("task2 interrupted: " + e);
}
}
};
pool.execute(task1);
for(int i=0; i<1000; ++i){
pool.execute(task2);
}
try {
pool.shutdown();
if(!pool.awaitTermination(awaitTime, TimeUnit.MILLISECONDS)){
pool.shutdownNow();
}
} catch (InterruptedException e) {
System.out.println("awaitTermination interrupted: " + e);
pool.shutdownNow();
}
System.out.println("end");
}
blog.csdn.net/zaozi/artic…
ScheduledExecutorService
private ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.execute(new Runnable() {
@Override
public void run() {
}
});