簡體   English   中英

我需要在這里檢查Thread.isAlive()嗎?

[英]Do I need to check for Thread.isAlive() here?

在Web控制器中,我有一個接收請求的父線程。 有些請求需要很長時間才能處理。 為了防止客戶端超時,我設置父線程每2秒發送一個字節,而子線程正在執行耗時的操作部分。

我想確保我考慮到子線程死亡的所有可能情況,但我也不想進行任何無關的檢查。

這是父線程:

    // This is my runnable class
    ProcessorRunnable runnable = new ProcessorRunnable(settings, Thread.currentThread());
    Thread childThread = new Thread(runnable);
    childThread.start();

    boolean interrupted = false;
    while (!runnable.done) { // <-- Check in question
        outputStream.write(' ');
        outputStream.flush();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // If the runnable is done, then this was an expected interrupt
            // Otherwise, remember the interruption and re-interrupt after processing is done
            // Or with self so that a later expected interrupt won't clear out an earlier unexpected one
            interrupted = interrupted || !runnable.done;
        }
    }
    if (runnable.runtimeException != null) {
        LOG.error("Propagating runtime exception from thread");
        throw runnable.runtimeException;
    }

    // ... Further processing on the results provided by the child thread

這里是ProcessorRunnable:

    private volatile boolean done;
    private volatile Result result;
    private volatile RuntimeException runtimeException;

    // ...

    public void run() {
        done = false;
        try {
            result = myService.timeConsumingOperation(settings);
        } catch (RuntimeException e) {
            runtimeException = e;
        } finally {
            done = true;
            parentThread.interrupt();
        }
    }

我的問題是,在父線程的主循環中添加&& Thread.isAlive()檢查會給我帶來什么嗎? 似乎在finally塊中設置done = true應該可以解決問題,但是在某些情況下,這個子線程可能會死而不通知父級嗎?

子線程中的finally將始終在完成之前執行。 即使該線程被中斷或停止,這也會發生異常,它會使調用堆棧冒泡並finally觸發所有s。 因此,如果子線程被中斷,則done將始終為true。

對於像這樣的后台任務,您可能希望使用ExecutorService而不是原始線程。 您可以向ExecutorService提交Runnable ,並在返回的future上調用get()直到它完成為止。 如果要在等待時打印出空格,可以使用循環,以超時方式調用get()版本。

暫無
暫無

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

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