簡體   English   中英

Java等待可運行的完成

[英]Java wait for runnable to finish

我有一個將以無限循環啟動Runnable的類。 在某個時候,我想關閉程序,並且要以一種干凈的方式進行操作(例如,確保在執行結束時線程將刷新一些緩沖區以輸出文件等)。 我該怎么做?

注意:在注釋中,我寫了// Version 1// Version 2 那是因為我嘗試了兩個版本,但都沒有用,所以我不斷收到InterruptedException。

主類:

public class MainClass {

    private static Thread myThread;
    private static MyRunnable myRunnable;
    private static Logger logger;

    public static void main( String[] args ) {
        ...
        myRunnable = new MyRunnable(logger);
        myThread = new Thread(myRunnable);
        myThread.start();
        ...
    }

    private static void shutDown() {
        logger.debug("Shut down everything.");
        if(myRunnable != null){
            myRunnable.shutdown();
            try {
                myThread.join();
                logger.debug("Runnable Stopped");
            } catch (InterruptedException e) { // Always failing here
                e.printStackTrace();
            }
        }
        // Now stop logger and other things
        logger.debug("Shutdown other stuff");
        ...
        logger.debug("Shutdown logger");
        Configurator.shutdown((LoggerContext)LogManager.getContext());
        System.out.println("Done");
    }
}

可運行類:

public class MyRunnable implements Runnable {

    private AtomicBoolean stop = new AtomicBoolean(false); // Version 1

    public boolean isStopped() { 
        return stop.get(); // Version 1
        return Thread.currentThread().isInterrupted(); // Version 2
    }

    public void shutdown() {
        logger.debug("Stopping my runnable");
        stop.set(true); // Version 1
        Thread.currentThread().interrupt(); // Version 2
    }

    @Override
    public void run() {
        try{
            while(!isStopped()) {
                // Do things
            }
            logger.debug("Exiting from infinite loop");
        } catch(Exception e){
            logger.error("Exception! " + e.getMessage());
        } finally {
            logger.debug("Entering in finally part");
            // Flush buffer, commit to database, ... close stuff
        }
    }
}

但是shutDown函數的輸出始終是相同的:

Shut down everything.
java.lang.InterruptedException
    at java.lang.Object.wait(Native Method)
    at java.lang.Thread.join(Thread.java:1260)
    at java.lang.Thread.join(Thread.java:1334)
    at com.my.packageName.MainClass.shutDown(MainClass.java:374)
Shutdown other stuff
Shutdown logger
Done

如果刪除join()函數,則異常消失,但輸出仍然相同。


編輯:我只是注意到,如果我注釋行myRunnable.shutdown(); 然后繼續執行myThread.join(); 即使我沒有停止該線程,我仍然會得到例外。 這是為什么? 是因為Tread和Runnable是兩個獨立的東西嗎? 如果是這樣,那么我如何停止Runnable並等待其完成?

在“版本2”中,您正在中斷正在調用stopParser()的線程,而不是正在執行run()的線程。 代替調用Thread.currentThread().interrupt() ,請使用myThread.interrupt()

我不知道為什么在“版本1”中會出現InterruptedException; 您必須在其他地方調用Thread.currentThread().interrupt() 僅當檢測到當前線程已被另一個線程中斷但不能立即終止該線程時,才應這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM