日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

Android 自定义线程池的实战

發(fā)布時間:2024/9/30 Android 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android 自定义线程池的实战 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
前言:在上一篇文章中我們講到了AsyncTask的基本使用、AsyncTask的封裝、AsyncTask 的串行/并行線程隊列、自定義線程池、線程池的快速創(chuàng)建方式。

對線程池不了解的同學可以先看?Android AsyncTask 深度理解、簡單封裝、任務隊列分析、自定義線程池?

?

-------------------------------------------------------------------------------------------------------

1、Executor 簡介

? ? ?在Java 5之后,并發(fā)編程引入了一堆新的啟動、調(diào)度和管理線程的API。Executor框架便是Java 5中引入的,其內(nèi)部使用了線程池機制,它在java.util.cocurrent 包下,通過該框架來控制線程的啟動、執(zhí)行和關閉,可以簡化并發(fā)編程的操作。因此,在Java 5之后,通過Executor來啟動線程比使用Thread的start方法更好,除了更易管理,效率更好(用線程池實現(xiàn),節(jié)約開銷)外,還有關鍵的一點:有助于避免this逃逸問題——如果我們在構造器中啟動一個線程,因為另一個任務可能會在構造器結束之前開始執(zhí)行,此時可能會訪問到初始化了一半的對象用Executor在構造器中。

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

? ?在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); }

  

2、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 對象作為參數(shù),并且以異步的方式執(zhí)行它。如下是一個使用 ExecutorService 執(zhí)行 Runnable 的例子

package com.app;import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;public class ExecutorTest {public static void main(String[] args) {//創(chuàng)建一個線程數(shù)固定大小為10的線程池ExecutorService executorService = Executors.newFixedThreadPool( 10 ) ;//執(zhí)行一個任務 該任務是 new Runnable() 對象executorService.execute( new Runnable() {@Overridepublic void run() {Log.d( Thread.currentThread().getName() ); }});//關閉線程池executorService.shutdown();} }

  結果:

pool-1-thread-1

? ? ?使用這種方式?jīng)]有辦法獲取執(zhí)行 Runnable 之后的結果,如果你希望獲取運行之后的返回值,就必須使用 接收 Callable 參數(shù)的 execute() 方法,后者將會在下文中提到。

?

? ? ?2.2、submit(Runnable)

? ? ? ??方法 submit(Runnable) 同樣接收一個 Runnable 的實現(xiàn)作為參數(shù),但是會返回一個 Future 對象。這個 Future 對象可以用于判斷 Runnable 是否結束執(zhí)行。如下是一個 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) {//創(chuàng)建一個線程數(shù)固定大小為10的線程池ExecutorService executorService = Executors.newFixedThreadPool( 10 ) ;//執(zhí)行一個任務 該任務是 new Runnable() 對象Future future = executorService.submit( new Runnable() {@Overridepublic void run() {Log.d( Thread.currentThread().getName() ); }});try {//如果任務結束執(zhí)行則返回 nullLog.d( ""+ future.get() ); } catch (Exception e) {e.printStackTrace();} //關閉線程池executorService.shutdown();} }

  結果:

pool-1-thread-1
null

? ?

? ? ?2.3?submit(Callable)

? ? ? ?方法 submit(Callable) 和方法 submit(Runnable) 比較類似,但是區(qū)別則在于它們接收不同的參數(shù)類型。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) {//創(chuàng)建一個線程數(shù)固定大小為10的線程池ExecutorService executorService = Executors.newFixedThreadPool( 10 ) ;//執(zhí)行一個任務 該任務是 new Callable() 對象Future future = executorService.submit( new Callable<String>() {@Overridepublic String call() throws Exception {return "執(zhí)行完了" ;}}) ;try {//如果任務結束執(zhí)行則返回 Log.d( "結果是: "+ future.get() ); } catch (Exception e) {e.printStackTrace();} //關閉線程池executorService.shutdown();} }

  結果:

結果是: 執(zhí)行完了

?

? ?2.4、inVokeAny()

? ? ? ?方法 invokeAny() 接收一個包含 Callable 對象的集合作為參數(shù)。調(diào)用該方法不會返回 Future 對象,而是返回集合中某一個 Callable 對象的結果,而且無法保證調(diào)用之后返回的結果是哪一個 Callable,只知道它是這些 Callable 中一個執(zhí)行結束的 Callable 對象。如果一個任務運行完畢或者拋出異常,方法會取消其它的 Callable 的執(zhí)行。

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) {//創(chuàng)建一個線程數(shù)固定大小為10的線程池ExecutorService executorService = Executors.newFixedThreadPool( 10 ) ;List<Callable<String>> list = new ArrayList<>() ;//創(chuàng)建第一個 CallableCallable<String> callable1 = new Callable<String>() {@Overridepublic String call() throws Exception {Log.d( "callable 1 線程是: "+ Thread.currentThread().getName() ); return "執(zhí)行完了 callable 1" ;}};//創(chuàng)建第二個 CallableCallable<String> callable2 = new Callable<String>() {@Overridepublic String call() throws Exception {Log.d( "callable 2 線程是: "+ Thread.currentThread().getName() ); return "執(zhí)行完了 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
結果是: 執(zhí)行完了 callable 2

? ? ?總結:

? ? ? ?1、可以看到?Callable 里面的call方法,都是在子線程中運行的,

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

?

? ? 2.5、invokeAll()

?方法 invokeAll() 會調(diào)用存在于參數(shù)集合中的所有 Callable 對象,并且返回一個包含 Future 對象的集合,你可以通過這個返回的集合來管理每個 Callable 的執(zhí)行結果。需要注意的是,任務有可能因為異常而導致運行結束,所以它可能并不是真的成功運行了。但是我們沒有辦法通過 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) {//創(chuàng)建一個線程數(shù)固定大小為10的線程池ExecutorService executorService = Executors.newFixedThreadPool( 10 ) ;List<Callable<String>> list = new ArrayList<>() ;//創(chuàng)建第一個 CallableCallable<String> callable1 = new Callable<String>() {@Overridepublic String call() throws Exception {Log.d( "callable 1 線程是: "+ Thread.currentThread().getName() ); return "執(zhí)行完了 callable 1" ;}};//創(chuàng)建第二個 CallableCallable<String> callable2 = new Callable<String>() {@Overridepublic String call() throws Exception {Log.d( "callable 2 線程是: "+ Thread.currentThread().getName() ); return "執(zhí)行完了 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
結果是: 執(zhí)行完了 callable 1
結果是: 執(zhí)行完了 callable 2

? ? 注意:1:Callable 的call方法都是執(zhí)行在子線程中的

? ? ? ? ? ? 2:?executorService.invokeAll( list ) 是返回值。 但是必須是所有的 Callable對象執(zhí)行完了,才會返回,返回值是一個list, 順序和 List<Callable>一樣 。在執(zhí)行的過程中,如果任何一個Callable發(fā)生異常,程序會崩潰,沒有返回值。

? ? ? ?

? ? ?2.6 如何關閉?ExecuteService 服務 ?

當使用 ExecutorService 完畢之后,我們應該關閉它,這樣才能保證線程不會繼續(xù)保持運行狀態(tài)。?舉例來說,如果你的程序通過 main() 方法啟動,并且主線程退出了你的程序,如果你還有一個活動的 ExecutorService 存在于你的程序中,那么程序將會繼續(xù)保持運行狀態(tài)。存在于 ExecutorService 中的活動線程會阻Java虛擬機關閉。?

為了關閉在 ExecutorService 中的線程,你需要調(diào)用 shutdown() 方法。ExecutorService 并不會馬上關閉,而是不再接收新的任務,一旦所有的線程結束執(zhí)行當前任務,ExecutorServie 才會真的關閉。所有在調(diào)用 shutdown() 方法之前提交到 ExecutorService 的任務都會執(zhí)行。?
如果你希望立即關閉 ExecutorService,你可以調(diào)用 shutdownNow() 方法。這個方法會嘗試馬上關閉所有正在執(zhí)行的任務,并且跳過所有已經(jīng)提交但是還沒有運行的任務。但是對于正在執(zhí)行的任務,是否能夠成功關閉它是無法保證 的,有可能他們真的被關閉掉了,也有可能它會一直執(zhí)行到任務結束。這是一個最好的嘗試。?

?

與50位技術專家面對面20年技術見證,附贈技術全景圖

總結

以上是生活随笔為你收集整理的Android 自定义线程池的实战的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。