ScheduledThreadPoolExecutor淺談

      ScheduledThreadPoolExecutor稱作多線程調度器,繼承自ThreadPoolExecutor,添加了按計劃執行線程操作的功能,如:延遲,定時,週期執行任務。

     一、它繼承自ThreadPoolExecutor,首先來看看它的家族。

      

      二、調度方法

      (1)schedule(Runnable , delay, TimeUnit):延遲執行任務

     (2)scheduleAtFixedRate(Runnable , delay, period, TimeUnit):定期執行任務,若執行任務時間超過指定週期時間period,則執行完畢後會立即執行下次任務。

     (3)scheduleWithFixedDelay(Runnable , delay, period , TimeUnit):也是定期執行任務,差別在於該方法period是指每次執行完畢後,間隔period時間,在執行下次任務。

    

     三、與Timer比較

     Timer的缺點:

     (1)Timer內部只創建了一個線程,如果某個任務耗時,就會影響其他的任務執行。

     (2)Timer沒有處理異常,在跑多個任務時,只要其中之一沒有捕獲異常,其他的任務也會終止。

     故jdk1.5後推薦使用ScheduledThreadPoolExecutor來代替Timer。


   四、ThreadPoolExecutor的使用

final ScheduledThreadPoolExecutor poolExecutor = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
            @Override
            public Thread newThread(@NonNull Runnable runnable) {
                Thread thread = new Thread(runnable);
                //設置爲守護線程
                thread.setDaemon(true);
                thread.setName("Thread--001");
                return thread;
            }
        });

final long startTime = System.currentTimeMillis();
        poolExecutor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                long endTime = System.currentTimeMillis();
                final long time = (endTime - startTime) / 1000;
                Log.i(initTag(), "time:" + time);
                if (time >= 5) {
                    poolExecutor.shutdown();
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            thread_tv1.setText(time + "");
                        }
                    });
                }
            }
        }, 0, 1, TimeUnit.SECONDS);

  五、守護線程與用戶線程

   thread.setDaemon(true)即爲將該線程設置爲守護線程;相反設置爲true即爲用戶線程,默認爲用戶線程。

  區別:守護線程也稱服務線程,優先級比較低。如果程序中用戶線程有結束了,程序也會退出,不管守護線程是否結束,但只要有一個user線程,程序就不會退出。垃圾回收線程就是一個守護線程,如果程序中沒有了運行的thread,那麼改程序也就沒有垃圾可供回收,回收線程就會自動離開。

主意一點:setDaemon(boolean)方法一定要在thread.start()之前,否則線程啓動後設置無效。




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章