java 关闭main方法中的定时器线程(2)


import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by cloud.huang on 16/5/20.
 */
public class ScheduledThreadPoolCloseTest {

    public static void main(String[] args) throws Exception {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(3);

        executor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println("start" + "====" + Thread.currentThread().getName());
                int i = 0;
                while (true) {
                    i++;
                    System.out.println(i + "====" + Thread.currentThread().getName());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        break;
                    }
                }
            }
        }, 1, 1, TimeUnit.SECONDS);


        Thread.sleep(2000);
        System.out.println("close begain");
        // executor.shutdown(); // 这个是不可以的 停不下来的
        executor.shutdownNow(); // 这个配合catch 中的break是可以的

    }

}



使用线程池的话,只能用shutdown 或shutdownNow 关闭。shutdownNow会打断运行中的任务,当然还是要任务自己捕捉InterruptedException 自己退出

猜你喜欢

转载自huangyunbin.iteye.com/blog/2299577