繁体   English   中英

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

[英]ScheduleAtFixedRate executes once (or as many times as corePoolSize equals)

我已经创建了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);

我想念什么? 我究竟做错了什么?

如果在运行可运行程序时发生运行时异常而没有引发异常,则ScheduledExecutorService阻止后续调用(真的很难过)。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM