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);
我缺少什么?我究竟做错了什么?如果在没有抛出异常(真正悲伤)执行可运行发生运行时异常