Java并发-在调用`ExecutorService#execute`之前添加一个Shutdown挂钩

时间:2018-10-29 09:58:27

标签: java multithreading executorservice

我有一个可运行的线程MyDesiredRunnable,其运行如下:

public void run() {
    try {
        this.process();
    } catch (InterruptedException e) {
        isAlive.set(false);
    }
}

isAliveAtomicBoolean

计划程序:

// Class definition bla bla bla
   private final ExecutorService exth = Executors.newSingleThreadExecutor();

public void schedule() {
    Runnable r = new MyDesiredRunnable();
    Runnable sdt = ()->{MyDesiredRunnable.isAlive.set(false);};

    Runtime.getRuntime().addShutdownHook(new Thread(sdt));
    this.exth.execute(r);
}

此调度程序将始终仅是一个实例。我的问题是,“在调用execute之前是否添加关闭挂钩是否重要。我从javadocs可以理解的是,只有在命令了JVM关闭之后,关闭挂钩才能解决。而且,{{1 }}命令似乎也没说什么反对在之前/之后使用关机钩子,只是SO上的一些execute示例,甚至有些书在我们调用execute之后都进行了关机钩子注册。只是想知道是否存在我不理解的“赶上”。

谢谢

1 个答案:

答案 0 :(得分:0)

为避免尝试检测任务是否间接运行,可以使用线程本身。如果线程不活跃,则您的任务没有运行。

class ThreadedRunnable implements Runnable {
    volatile boolean started = false;
    volatile Thread thread;
    Runnable runnable;

    ThreadedRunnable(Runnable runnable) { this.runnable = runnable; }

    public void run() {
        thread = Thread.currentThread();
        started = true;
        try {
            runnable.run();
        } catch (Throwable t) { // don't silently discard it
            logger.error(runnable + " died", t);
        } finally {
            thread = null;
        }
    }

    public String state() { // or return an Enum
        Thread t = thread;
        return !started ? "not started" :
               t == null || !t.isAlive() ? "finished" : "running";
    }
}