我正在尝试查找有关如何约束使用ThreadPoolExecutor创建的任务的运行时间的更多信息。
我想创建一个自毁,例如当时间过去(例如1m),然后线程将自动终止并返回空值。这里的关键点是等待线程完成不应该阻塞主线程(在我们的例子中的UI线程)。
我知道我可以使用get方法,但它会阻止我的应用程序。
我正在考虑运行一个额外的内部线程,它将休眠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.
}
}
}
通过ThreadPool调用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;
}
我害怕有几点:
您是否看到了更好的想法来实现相同的功能?
答案 0 :(得分:1)
这样做会涉及到一些问题。首先,您需要扩展ThreadPoolExecutor类。您需要覆盖“beforeExecute”和“afterExecute”方法。他们会跟踪线程的开始时间,并在之后进行清理。然后你需要一个收割机来定期检查哪些线程需要清理。
此示例使用Map记录每个线程的启动时间。 beforeExecute方法填充此方法,afterExecute方法清除它。有一个TimerTask定期执行并查看所有当前条目(即所有正在运行的线程),并在超过给定时间限制的所有条目上调用Thread.interrupt()。
请注意,我已经给出了两个额外的构造函数参数:maxExecutionTime和reaperInterval来控制任务的给定时间,以及检查要杀死的任务的频率。为了简洁起见,我在这里省略了一些构造函数。
请记住,您提交的任务必须发挥得很好,并让自己被杀死。这意味着你必须:
public class TimedThreadPoolExecutor extends ThreadPoolExecutor {
private Map<Thread, Long> threads = new HashMap<Thread, Long>();
private Timer timer;
public TimedThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue,
long maxExecutionTime,
long reaperInterval) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
startReaper(maxExecutionTime, reaperInterval);
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
threads.remove(Thread.currentThread());
System.out.println("after: " + Thread.currentThread().getName());
super.afterExecute(r, t);
}
@Override
protected void beforeExecute(Thread t, Runnable r) {
super.beforeExecute(t, r);
System.out.println("before: " + t.getName());
threads.put(t, System.currentTimeMillis());
}
@Override
protected void terminated() {
if (timer != null) {
timer.cancel();
}
super.terminated();
}
private void startReaper(final long maxExecutionTime, long reaperInterval) {
timer = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
// make a copy to avoid concurrency issues.
List<Map.Entry<Thread, Long>> entries =
new ArrayList<Map.Entry<Thread, Long>>(threads.entrySet());
for (Map.Entry<Thread, Long> entry : entries) {
Thread thread = entry.getKey();
long start = entry.getValue();
if (System.currentTimeMillis() - start > maxExecutionTime) {
System.out.println("interrupting thread : " + thread.getName());
thread.interrupt();
}
}
}
};
timer.schedule(timerTask, reaperInterval, reaperInterval);
}
public static void main(String args[]) throws Exception {
TimedThreadPoolExecutor executor = new TimedThreadPoolExecutor(5,5, 1000L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(20),
1000L,
200L);
for (int i=0;i<10;i++) {
executor.execute(new Runnable() {
public void run() {
try {
Thread.sleep(5000L);
}
catch (InterruptedException e) {
}
}
});
}
executor.shutdown();
while (! executor.isTerminated()) {
executor.awaitTermination(1000L, TimeUnit.MILLISECONDS);
}
}
}