绑定线程运行时间

时间:2012-05-26 22:40:35

标签: java multithreading threadpool

我正在尝试查找有关如何约束使用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;
}

我害怕有几点:

  • 如果execute()有异常会发生什么,之​​后我的外部线程会中断,然后我就永远不会发现异常。
  • 内存/ CPU消耗,我使用线程池来避免创建新线程。

您是否看到了更好的想法来实现相同的功能?

1 个答案:

答案 0 :(得分:1)

这样做会涉及到一些问题。首先,您需要扩展ThreadPoolExecutor类。您需要覆盖“beforeExecute”和“afterExecute”方法。他们会跟踪线程的开始时间,并在之后进行清理。然后你需要一个收割机来定期检查哪些线程需要清理。

此示例使用Map记录每个线程的启动时间。 beforeExecute方法填充此方法,afterExecute方法清除它。有一个TimerTask定期执行并查看所有当前条目(即所有正在运行的线程),并在超过给定时间限制的所有条目上调用Thread.interrupt()。

请注意,我已经给出了两个额外的构造函数参数:maxExecutionTime和reaperInterval来控制任务的给定时间,以及检查要杀死的任务的频率。为了简洁起见,我在这里省略了一些构造函数。

请记住,您提交的任务必须发挥得很好,并让自己被杀死。这意味着你必须:

  1. 定期检查Thread.currentThread()。isInterrupted() 在执行期间。
  2. 尽量避免任何未声明的阻止操作 它的throws子句中的InterruptedException。这是一个很好的例子 将是InputStream / OutputStream用法,您将使用NIO 而是渠道。如果必须使用这些方法,请在从此类操作返回后立即检查中断标志。
  3. 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);
            }
        }
    
    
    
    }
    
相关问题