繁体   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