我试图找到更多关于如何约束使用ThreadpoolExcutor 。
我想创建一个自毁装置, 例如, 当时间( 例如 1m) 过后, 线索会自动结束, 然后返回一个无效值 。 这里的关键点是等待线索完成时, 关键点不应该屏蔽主线( 我们示例中的 UI 线索) 。
我在想再开一条内部线 睡上1米 然后打断主线
我附加了一个示例代码, 它看起来像一个好主意, 但我需要另一对眼睛 告诉我,如果它有意义。
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.
}
}
}
() 被通过线索pool调用
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;
}
有两点我担心:
- What will happen if execute() has an exception and immediately afterwards my external thread will interrupt, then I ll never catch the exception.
- Memory/CPU consumption, I am using a thread pool to avoid the creation of new threads.
你看到一个更好的想法 达到相同的功能吗?