1 随机线程池,如果需要有几个任务就开启几个线程来执行任务
ExecutorService service = Executors.newCachedThreadPool();
2 固定线程池
ExecutorService service = Executors.newFixedThreadPool(3);
3单线程,这个比传统线程的好处在于,线程销毁了,可以自动活过来
ExecutorService service = Executors.newSingleThreadExecutor();
定时调度的线程
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
//command 所要执行的任务
//initialDelay 第一次启动时的延迟启动时间
//period 每隔多少时间执行任务
//unit 单位时间
scheduledExecutorService.scheduleAtFixedRate(new ViewPagerTask(), 1, 2, TimeUnit.SECONDS);
}
@Override
protected void onStop() {
scheduledExecutorService.shutdown();
super.onStop();
}
class ViewPagerTask implements Runnable{
@Override
public void run() {
currentItem = (currentItem + 1)% images.size();
handler.obtainMessage().sendToTarget();
}
}
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
viewPager.setCurrentItem(currentItem);
}
};