簡體   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