【发布时间】:2012-05-26 22:40:34
【问题描述】:
我正在尝试查找有关如何限制使用ThreadPoolExecutor 创建的任务的运行时间的更多信息。
我想创建一个自毁的,例如当时间过去(例如 1m)时,线程将自动终止并返回一个空值。这里的关键点是等待线程完成不应该阻塞主线程(在我们的例子中是 UI 线程)。
我知道我可以使用get 方法,但是它会阻止我的应用程序。
我正在考虑运行一个额外的内部线程,它会休眠 1m,然后会在主线程上调用中断。
我附上了一个示例代码,它看起来是个好主意,但我需要另一双眼睛告诉我它是否有意义。
public abstract class AbstractTask<T> implements Callable<T> {
private final class StopRunningThread implements Runnable {
/**
* Holds the main thread to interrupt. Cannot be null.
*/
private final Thread mMain;
public StopRunningThread(final Thread main) {
mMain = main;
}
@Override
public void run() {
try {
Thread.sleep(60 * 1000);
// Stop it.
mMain.interrupt();
} catch (final InterruptedException exception) {
// Ignore.
}
}
}
call() 通过线程池调用
public T call() {
try {
// Before running any task initialize the result so that the user
// won't
// think he/she has something.
mResult = null;
mException = null;
// Stop running thread.
mStopThread = new Thread(new StopRunningThread(
Thread.currentThread()));
mStopThread.start();
mResult = execute(); <-- A subclass implements this one
} catch (final Exception e) {
// An error occurred, ignore any result.
mResult = null;
mException = e;
// Log it.
Ln.e(e);
}
// In case it's out of memory do a special catch.
catch (final OutOfMemoryError e) {
// An error occurred, ignore any result.
mResult = null;
mException = new UncheckedException(e);
// Log it.
Ln.e(e);
} finally {
// Stop counting.
mStopThread.interrupt();
}
return mResult;
}
有几点我很害怕:
- 如果 execute() 发生异常,然后我的外部线程立即中断,我将永远无法捕获该异常。
- 内存/CPU消耗,我正在使用线程池来避免创建新线程。
您认为实现相同功能的更好主意吗?
【问题讨论】:
标签: java multithreading threadpool