2017-04-20 24 views
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); 

我缺少什麼?我究竟做錯了什麼?如果在沒有拋出異常(真正悲傷)執行可運行發生運行時異常

回答

0

ScheduledExecutorService塊後續調用。

這可能是您的問題。也許一些在代碼拋出異常,因此沒有更多的調用不會發生。嘗試在try catch中包裝runnable以查看是否有任何異常拋出。