ScheduleAtFixedRate执行一次(或者corePoolSize等于执行次数)

时间:2017-04-20 12:08:00

标签: java android multithreading

我创建了 MyThreadPoolExecutor

public class MyThreadPoolExecutor extends ScheduledThreadPoolExecutor {
    private final Context ctx;

    public MyThreadPoolExecutor(int corePoolSize, Context ctx, String threadNamePrefix)
    {
        super(corePoolSize);
        MyThreadFactory factory = new MyThreadFactory(new ThreadExceptionHandler(ctx), threadNamePrefix);
        setThreadFactory(factory);
        this.ctx = ctx;
    }

    @Override
    public void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        LogUtils.i(Tags.THREAD_EXECUTED, Thread.currentThread().getName());

        if (t == null && r instanceof Future<?>) {
            try {
                Object result = ((Future<?>) r).get();
            } catch (CancellationException e) {
                t = e;
            } catch (ExecutionException e) {
                t = e.getCause();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }

        if (t != null) {
            LogUtils.e(Tags.UNCAUGHT_EXCEPTION, "Uncaught exception error");
            Utils.handleUncaughtException(ctx, t);
        }
    }
}

我有MyThreadFactory

public class MyThreadFactory implements ThreadFactory {
private static final ThreadFactory defaultFactory = Executors.defaultThreadFactory();
private final Thread.UncaughtExceptionHandler handler;
private final String threadName;

public MyThreadFactory(Thread.UncaughtExceptionHandler handler, @NonNull String threadName) {
    this.handler = handler;
    this.threadName = threadName;
}

@Override
public Thread newThread(@NonNull Runnable runnable) {
    Thread thread = defaultFactory.newThread(runnable);
    thread.setUncaughtExceptionHandler(handler);
    if (threadName != null) {
        thread.setName(threadName +"-" + thread.getId());
    }
    LogUtils.i(Tags.THREAD_CREATED, thread.getName());
    return thread;
}

}

我需要每1秒执行一次线程来做一些事情。当我使用自己的MyScheduledThreadPoolExecutor时,它运行的次数与corePoolSize等于的次数相同。所以当corePoolSize等于3时,我的线程会运行3次。

当我使用ScheduledThreadPoolExecutor时,上述问题不存在。

在我运行它的方式下面:

commander = new MyThreadPoolExecutor(corePoolSize, getApplicationContext(), threadNamePrefix);
commander.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            LogUtils.i(Tags.DISPLAY_ACTIVITY, "Check display " + Thread.currentThread().getName());
        }
    }, 1000, PERIOD_CHECK_TIME_FRAME, TimeUnit.MILLISECONDS);

我错过了什么?我做错了什么?

1 个答案:

答案 0 :(得分:0)

如果在执行runnable时发生运行时异常而不抛出异常,则

ScheduledExecutorService会阻止后续调用(真的很难过)。

这可能是你的问题。可能是某些代码抛出异常的地方,因此不再发生调用。尝试将runnable包装在try catch中,以查看是否抛出任何异常。