0
我創建MyThreadPoolExecutorScheduleAtFixedRate執行一次(或多次corePoolSize等於)
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);
我缺少什麼?我究竟做錯了什麼?如果在沒有拋出異常(真正悲傷)執行可運行發生運行時異常