62,628
社区成员
发帖
与我相关
我的任务
分享
Runnable runnable2 = new Runnable() {
@Override
public void run() {
Log.d(TAG,"runnable2 run in thread "+Thread.currentThread().getId());
try {
//睡眠1min 为了便于观察结果
TimeUnit.SECONDS.sleep(60);
} catch (InterruptedException e) {
e.printStackTrace();
Log.d(TAG,"runnable2 is interrupted");
}
Log.d(TAG,"任务完成!");
}
};
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
scheduledExecutorService.schedule(runnable2,1,TimeUnit.SECONDS);
scheduledExecutorService.schedule(runnable2,1,TimeUnit.SECONDS);
//创建的时候核心线程数为2 因此任务数目大于2时会等待前面的任务执行完才会开始执行新任务
scheduledExecutorService.schedule(runnable2,1,TimeUnit.SECONDS);
scheduledExecutorService.shutdown();
/**
* Creates a new {@code ScheduledThreadPoolExecutor} with the
* given core pool size.
*
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
* @throws IllegalArgumentException if {@code corePoolSize < 0}
*/
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
核心线程就是即使空闲了也不会被回收的线程,即永久存在的线程,非核心线程是运行结束后空闲了就会被销毁的线程。