簡體   English   中英

Java並發-在調用`ExecutorService#execute`之前添加一個Shutdown掛鈎

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

我有一個可運行線程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關閉后,關閉鈎子才能被解決。而且, execute命令似乎也沒有說什么反對在關閉之前/之后使用關閉鈎子。僅僅是SO上的一些ExecutorService示例,甚至一些書在我們調用execute之后都發生了關閉鈎子注冊。所以我只想知道是否存在“捕獲”我不明白

謝謝,

為了避免嘗試檢測任務是否間接運行,可以使用線程本身。 如果線程不活躍,則您的任務未運行。

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