线程池shutdown与shutdownnow 小例子

如何理解shutdonw与shutdownnow,直接看一下我写的这个小例子:

//线程生产厂
public class MyThreadFactory implements ThreadFactory {

    private static AtomicInteger ai = new AtomicInteger(0);

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(r,"-my thread-" + ai.getAndIncrement());
        return t;
    }
}

//执行逻辑部分
public class InterruptThreadInPoolTest implements Runnable {


    @Override
    public void run(){
        System.out.println( Thread.currentThread().getName()+ " logic start ");

         // 核心部分
        if (Thread.currentThread().isInterrupted()) {
            System.out.println(Thread.currentThread().getName() + " was interrupted ....");
            //异常有了要记日志还是事物回滚 还不是由你掌握 - -
            throw new NullPointerException("随便丢出去一个异常!");
        }

        System.out.println(Thread.currentThread().getName() + " logic end");
    }

    public static void main(String[] args) {
        ThreadPoolExecutor t = new ThreadPoolExecutor(5
                , 5
                , 1000, TimeUnit.SECONDS
                , new ArrayBlockingQueue<>(5), new MyThreadFactory());
        for (int i = 0; i < 5; i++) {
            t.submit(new InterruptThreadInPoolTest());
        }
        t.shutdownNow();
        //t.shutdown();

    }
}

 执行完小例子,感觉秒懂呢。

猜你喜欢

转载自www.cnblogs.com/c--k/p/12934605.html