简体   繁体   English

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

[英]Java Concurrency - Adding a Shutdown hook before calling `ExecutorService#execute`

I have a runnable thread MyDesiredRunnable which has the following run: 我有一个可运行线程MyDesiredRunnable ,该线程具有以下运行:

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

isAlive is an AtomicBoolean . isAlive是一个AtomicBoolean

The Scheduler: 调度程序:

// 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);
}

This Scheduler will always be only one instance. 此调度程序将始终仅是一个实例。 My question is, "Does it matter if I add the shutdown hook before I call execute . All I can understand from javadocs is that the shutdown hook will not be resolved until JVM shutodown is commanded. Also, the execute command also doesn't seem to say anything against having a shutdown hook before/after. It's just that a few of ExecutorService examples on SO or even some books have the shutdownhook registration happening after we call execute. So I just wanted to know whether there is a "Catch" that I don't understand. 我的问题是,“在调用execute之前是否添加关闭钩子有关系吗?我从javadocs可以理解的是,只有在命令JVM关闭后,关闭钩子才能被解决。而且, execute命令似乎也没有说什么反对在关闭之前/之后使用关闭钩子。仅仅是SO上的一些ExecutorService示例,甚至一些书在我们调用execute之后都发生了关闭钩子注册。所以我只想知道是否存在“捕获”我不明白

Thanks, 谢谢,

To avoid trying to detect if the task is running indirectly you can use the Thread itself. 为了避免尝试检测任务是否间接运行,可以使用线程本身。 If the thread isn't alive, your task isn't running. 如果线程不活跃,则您的任务未运行。

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";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM