ThreadTool和scheduled

1 隨機線程池,若是須要有幾個任務就開啓幾個線程來執行任務 java

ExecutorService service = Executors.newCachedThreadPool(); ide

2 固定線程池 線程

ExecutorService service = Executors.newFixedThreadPool(3); code

3單線程,這個比傳統線程的好處在於,線程銷燬了,能夠自動活過來 get

ExecutorService service = Executors.newSingleThreadExecutor(); it

定時調度的線程 io

 

@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);
		}
    	
    };
相關文章
相關標籤/搜索