如果我致电退货会发生什么;来自Runnable?
我有Java Runnable,我正在执行run()
方法。在该运行方法中有一些与服务器连接的连接,当它失败时,我不再对线程执行感兴趣,我想退出它。我做这样的事情:如果我致电退货会发生什么;来自Runnable?
class MyRunnable implements Runnable {
@Override
public void run() {
// connect to server here
if (it failed) {
return;
}
// do something else
}
}
现在我提交此可运行为Executors.cachedThreadPool()
与我自己的线程工厂,基本上没有什么新东西。
我是安全的,从可运行这样的回报?
我看着jvisualvm,看到线程池中有一个线程+有线程正在执行与服务器逻辑的连接,当我返回时,我看到这些连接线程停止,它们停留在列表中,但它们是白色的......
你不提交线程执行者,您要提交的Runnable吧。在Runnable中调用返回不会导致执行它的线程终止。遗嘱执行人是这么写的,它可以在的Runnable的形式运行多个任务,当一个Runnable完成执行(不管它是否早返回或其他)的线程将继续,并且会从它的排队等候的更多的工作提交的任务。
下面是在的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);
}
}
是的,你是对的。我对此进行了测试,发现runnable可能会过早返回几次,并且在JVM的整个生命周期中仍然有一个线程在jvisualvm中处于活动状态,以便在闲置时重用线程。 – stewenson
这是完全正常使用return
从void
方法。它只是从该方法返回,在这种情况下将完成线程执行。
是的,它只是一个方法调用。回来很好。 –