Android 自定義線程池的實戰 Android AsyncTask 深度理解、簡單封裝、任務隊列分析、自定義線程池

前言:在上一篇文章中咱們講到了AsyncTask的基本使用、AsyncTask的封裝、AsyncTask 的串行/並行線程隊列、自定義線程池、線程池的快速建立方式。html

對線程池不瞭解的同窗能夠先看 Android AsyncTask 深度理解、簡單封裝、任務隊列分析、自定義線程池 java

 

-------------------------------------------------------------------------------------------------------編程

一、Executor 簡介

     在Java 5以後,併發編程引入了一堆新的啓動、調度和管理線程的API。Executor框架即是Java 5中引入的,其內部使用了線程池機制,它在java.util.cocurrent 包下,經過該框架來控制線程的啓動、執行和關閉,能夠簡化併發編程的操做。所以,在Java 5以後,經過Executor來啓動線程比使用Thread的start方法更好,除了更易管理,效率更好(用線程池實現,節約開銷)外,還有關鍵的一點:有助於避免this逃逸問題——若是咱們在構造器中啓動一個線程,由於另外一個任務可能會在構造器結束以前開始執行,此時可能會訪問到初始化了一半的對象用Executor在構造器中。併發

   Executor框架包括:線程池,Executor,Executors,ExecutorService,CompletionService,Future,Callable等。app

   在java代碼中 Executor是一個接口,只有一個方法。框架

public interface Executor {

    /**
     * Executes the given command at some time in the future.  The command
     * may execute in a new thread, in a pooled thread, or in the calling
     * thread, at the discretion of the {@code Executor} implementation.
     *
     * @param command the runnable task
     * @throws RejectedExecutionException if this task cannot be
     * accepted for execution
     * @throws NullPointerException if command is null
     */
    void execute(Runnable command);
}

  

二、ExecutorService 

     ExecutorService 是一個接口,繼承 Executor ,除了有execute( Runnable command) 方法外,還拓展其餘的方法:    異步

public interface ExecutorService extends Executor {

}
  • void shutdown();
  • List<Runnable> shutdownNow();
  • boolean isShutdown();
  • boolean isTerminated();
  • boolean awaitTermination(long timeout, TimeUnit unit)
    throws InterruptedException;
  • <T> Future<T> submit(Callable<T> task);             //提交一個任務
  • <T> Future<T> submit(Runnable task, T result);      //提交一個任務
  • Future<?> submit(Runnable task);                    //提交一個任務
  • <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
    throws InterruptedException;
  • <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
    long timeout, TimeUnit unit)
    throws InterruptedException;
  • <T> T invokeAny(Collection<? extends Callable<T>> tasks)
    throws InterruptedException, ExecutionException;
  • <T> T invokeAny(Collection<? extends Callable<T>> tasks,
    long timeout, TimeUnit unit)
    throws InterruptedException, ExecutionException, TimeoutException;

   2.1 execute(Runnable)

        接收一個 java.lang.Runnable 對象做爲參數,而且以異步的方式執行它。以下是一個使用 ExecutorService 執行 Runnable 的例子ide

package com.app;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorTest {
	
	public static void main(String[] args) {
		
		//建立一個線程數固定大小爲10的線程池
		ExecutorService executorService = Executors.newFixedThreadPool( 10 ) ;
		
		//執行一個任務  該任務是 new Runnable() 對象
		executorService.execute( new Runnable() {
			
			@Override
			public void run() {
              Log.d( Thread.currentThread().getName() );				
			}
		});
		
		//關閉線程池
		executorService.shutdown();

	}
}

  結果:post

pool-1-thread-1this

     使用這種方式沒有辦法獲取執行 Runnable 以後的結果,若是你但願獲取運行以後的返回值,就必須使用 接收 Callable 參數的 execute() 方法,後者將會在下文中提到。

 

     2.二、submit(Runnable)

        方法 submit(Runnable) 一樣接收一個 Runnable 的實現做爲參數,可是會返回一個 Future 對象。這個 Future 對象能夠用於判斷 Runnable 是否結束執行。以下是一個 ExecutorService 的 submit() 方法的例子:

package com.app;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ExecutorTest {
	public static void main(String[] args) {

		//建立一個線程數固定大小爲10的線程池
		ExecutorService executorService = Executors.newFixedThreadPool( 10 ) ;

		//執行一個任務  該任務是 new Runnable() 對象
		Future future = executorService.submit( new Runnable() {
			@Override
			public void run() {
				Log.d( Thread.currentThread().getName() );	

			}
		});

		try {
			//若是任務結束執行則返回 null
			Log.d( ""+ future.get() );	
		} catch (Exception e) {
			e.printStackTrace();
		} 

		//關閉線程池
		executorService.shutdown();

	}
}

  結果:

pool-1-thread-1
null

   

     2.3 submit(Callable)

       方法 submit(Callable) 和方法 submit(Runnable) 比較相似,可是區別則在於它們接收不一樣的參數類型。Callable 的實例與 Runnable 的實例很相似,可是 Callable 的 call() 方法能夠返回壹個結果。方法 Runnable.run() 則不能返回結果。

      Callable 的返回值能夠從方法 submit(Callable) 返回的 Future 對象中獲取。以下是一個 ExecutorService Callable 的例子:

package com.app;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ExecutorTest {
	public static void main(String[] args) {

		//建立一個線程數固定大小爲10的線程池
		ExecutorService executorService = Executors.newFixedThreadPool( 10 ) ;

		//執行一個任務  該任務是 new Callable() 對象
		Future future  = executorService.submit( new Callable<String>() {

			@Override
			public String call() throws Exception {
				return "執行完了" ;
			}
		}) ;
	
		try {
			//若是任務結束執行則返回 
			Log.d( "結果是: "+ future.get() );	
		} catch (Exception e) {
			e.printStackTrace();
		} 

		//關閉線程池
		executorService.shutdown();

	}
}

  結果:

結果是: 執行完了

 

   2.四、inVokeAny()

       方法 invokeAny() 接收一個包含 Callable 對象的集合做爲參數。調用該方法不會返回 Future 對象,而是返回集合中某一個 Callable 對象的結果,並且沒法保證調用以後返回的結果是哪個 Callable,只知道它是這些 Callable 中一個執行結束的 Callable 對象。若是一個任務運行完畢或者拋出異常,方法會取消其它的 Callable 的執行。

package com.app;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorTest {
	public static void main(String[] args) {

		//建立一個線程數固定大小爲10的線程池
		ExecutorService executorService = Executors.newFixedThreadPool( 10 ) ;


		List<Callable<String>> list = new ArrayList<>() ;
		
		//建立第一個 Callable
		Callable<String> callable1 = new Callable<String>() {

			@Override
			public String call() throws Exception {
				Log.d( "callable 1 線程是: "+ Thread.currentThread().getName()  );	
				return "執行完了 callable 1" ;
			}
		};
		
		//建立第二個 Callable
		Callable<String> callable2 = new Callable<String>() {

			@Override
			public String call() throws Exception {
				Log.d( "callable 2 線程是: "+ Thread.currentThread().getName()  );	
				return "執行完了 callable 2" ;
			}
		};
		
		list.add( callable1 ) ;
		list.add( callable2 ) ;
		
		try {
		 String result = executorService.invokeAny( list ) ;
		 Log.d( "結果是: "+ result  );	
		} catch (InterruptedException e1) {
			
			e1.printStackTrace();
		} catch (ExecutionException e1) {
			e1.printStackTrace();
		}
	
		//關閉線程池
		executorService.shutdown();

	}
}

  結果:

callable 1 線程是: pool-1-thread-1

callable 2 線程是: pool-1-thread-2
結果是: 執行完了 callable 2

     總結:

       一、能夠看到 Callable 裏面的call方法,都是在子線程中運行的,

         二、 executorService.invokeAny( list ) ;返回值是任意一個 Callable 的返回值 。具體是哪個,每一個都有可能。

 

    2.五、invokeAll()

 方法 invokeAll() 會調用存在於參數集合中的全部 Callable 對象,而且返回一個包含 Future 對象的集合,你能夠經過這個返回的集合來管理每一個 Callable 的執行結果。須要注意的是,任務有可能由於異常而致使運行結束,因此它可能並非真的成功運行了。可是咱們沒有辦法經過 Future 對象來了解到這個差別。

package com.app;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ExecutorTest {
	public static void main(String[] args) {

		//建立一個線程數固定大小爲10的線程池
		ExecutorService executorService = Executors.newFixedThreadPool( 10 ) ;


		List<Callable<String>> list = new ArrayList<>() ;

		//建立第一個 Callable
		Callable<String> callable1 = new Callable<String>() {

			@Override
			public String call() throws Exception {
				Log.d( "callable 1 線程是: "+ Thread.currentThread().getName()  );	
				return "執行完了 callable 1" ;
			}
		};

		//建立第二個 Callable
		Callable<String> callable2 = new Callable<String>() {

			@Override
			public String call() throws Exception {
				Log.d( "callable 2 線程是: "+ Thread.currentThread().getName()  );	
				return "執行完了 callable 2" ;
			}
		};

		list.add( callable1 ) ;
		list.add( callable2 ) ;


		List<Future<String>> result;
		try {
			result = executorService.invokeAll( list );

			for (Future<String> future : result) {
				Log.d( "結果是: "+ future.get()  );	
			}	
		} catch (Exception e) {
			e.printStackTrace();
		}

		//關閉線程池
		executorService.shutdown();

	}
}

  結果

callable 1 線程是: pool-1-thread-1
callable 2 線程是: pool-1-thread-2
結果是: 執行完了 callable 1
結果是: 執行完了 callable 2

    注意:1:Callable 的call方法都是執行在子線程中的

            2: executorService.invokeAll( list ) 是返回值。 可是必須是全部的 Callable對象執行完了,纔會返回,返回值是一個list, 順序和 List<Callable>同樣 。在執行的過程當中,若是任何一個Callable發生異常,程序會崩潰,沒有返回值。

       

     2.6 如何關閉 ExecuteService 服務 ?

當使用 ExecutorService 完畢以後,咱們應該關閉它,這樣才能保證線程不會繼續保持運行狀態。 舉例來講,若是你的程序經過 main() 方法啓動,而且主線程退出了你的程序,若是你還有一個活動的 ExecutorService 存在於你的程序中,那麼程序將會繼續保持運行狀態。存在於 ExecutorService 中的活動線程會阻Java虛擬機關閉。 

爲了關閉在 ExecutorService 中的線程,你須要調用 shutdown() 方法。ExecutorService 並不會立刻關閉,而是再也不接收新的任務,一旦全部的線程結束執行當前任務,ExecutorServie 纔會真的關閉。全部在調用 shutdown() 方法以前提交到 ExecutorService 的任務都會執行。 
若是你但願當即關閉 ExecutorService,你能夠調用 shutdownNow() 方法。這個方法會嘗試立刻關閉全部正在執行的任務,而且跳過全部已經提交可是尚未運行的任務。可是對於正在執行的任務,是否可以成功關閉它是沒法保證 的,有可能他們真的被關閉掉了,也有可能它會一直執行到任務結束。這是一個最好的嘗試。 

相關文章
相關標籤/搜索