我在实现run()方法的地方有Java Runnable。在该运行方法中与服务器建立了某种连接,当服务器确实失败时,我对线程执行不再感兴趣,并且我想退出它。我做这样的事情:

class MyRunnable implements Runnable {
    @Override
    public void run() {
        // connect to server here
        if (it failed) {
            return;
        }

        // do something else
    }
}

现在,我使用自己的线程工厂将此可运行对象提交到Executors.cachedThreadPool()中,该线程工厂基本上没有任何新内容。

我可以安全地从那种可运行状态返回吗?

我查看了jvisualvm,发现线程池中有一个线程+在与服务器逻辑的连接中正在执行的线程,当我返回时,我看到这些连接线程已停止,它们确实保留在列表中,但是他们是白色的...

最佳答案

您不是将线程提交给执行者,而是将Runnables提交给执行者。在Runnable中调用return不会导致执行它的线程终止。编写执行程序,以便当Runnable完成执行(无论它是否提早返回)时,它可以以Runnables的形式运行多个任务,并继续执行线程,并从排队的已提交任务中获取更多工作。

这是ThreadPoolExecutor#runWorker方法中的代码。显示task.run()的行是工作线程执行任务的位置,当您的任务返回时,工作线程的执行将从那里开始。

final void runWorker(Worker w) {
    Thread wt = Thread.currentThread();
    Runnable task = w.firstTask;
    w.firstTask = null;
    w.unlock(); // allow interrupts
    boolean completedAbruptly = true;
    try {
        while (task != null || (task = getTask()) != null) {
            w.lock();
            // If pool is stopping, ensure thread is interrupted;
            // if not, ensure thread is not interrupted.  This
            // requires a recheck in second case to deal with
            // shutdownNow race while clearing interrupt
            if ((runStateAtLeast(ctl.get(), STOP) ||
                 (Thread.interrupted() &&
                  runStateAtLeast(ctl.get(), STOP))) &&
                !wt.isInterrupted())
                wt.interrupt();
            try {
                beforeExecute(wt, task);
                Throwable thrown = null;
                try {
                    task.run();
                } catch (RuntimeException x) {
                    thrown = x; throw x;
                } catch (Error x) {
                    thrown = x; throw x;
                } catch (Throwable x) {
                    thrown = x; throw new Error(x);
                } finally {
                    afterExecute(task, thrown);
                }
            } finally {
                task = null;
                w.completedTasks++;
                w.unlock();
            }
        }
        completedAbruptly = false;
    } finally {
        processWorkerExit(w, completedAbruptly);
    }
}

10-08 08:10