代码之家  ›  专栏  ›  技术社区  ›  ha9u63a7

Java并发性——在调用“ExecutorService#execute”之前添加一个关闭钩子`

  •  0
  • ha9u63a7  · 技术社区  · 5 年前

    我有一根可以穿的线 MyDesiredRunnable 其运行方式如下:

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

    isAlive 是一个 AtomicBoolean .

    调度程序:

    // 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 shutodown之前,关闭钩子不会被解决。还有 处决 命令似乎也没有反对在之前/之后使用关机挂钩。只是其中一些 ExecutorService 例如,在我们调用execute之后,甚至在一些书籍上都会发生关闭钩子注册。所以我只是想知道是否有我不明白的“陷阱”。

    谢谢

    1 回复  |  直到 5 年前
        1
  •  0
  •   Peter Lawrey    5 年前

    为了避免试图检测任务是否在间接运行,可以使用线程本身。如果线程未激活,则表示任务未运行。

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