首頁技術(shù)文章正文

Executor接口實(shí)現(xiàn)線程池管理

更新時(shí)間:2022-05-20 來源:黑馬程序員 瀏覽量:

從JDK5開始,在java.util.concurrent包下增加了Executor接口及其子類,允許使用線程池技術(shù)來管理線程并發(fā)問題。Executor接口提供了一個(gè)常用的ExecutorService子接口,通過該子接口可以很方便地進(jìn)行線程池管理。

通過Executor接口實(shí)現(xiàn)線程池管理的主要步驟如下:

(1)創(chuàng)建一個(gè)實(shí)現(xiàn)Runnable接口或者Callable接口的實(shí)現(xiàn)類,同時(shí)重寫run()或者call()方法;

(2)創(chuàng)建Runnable接口或者Callable接口的實(shí)現(xiàn)類對(duì)象;

(3)使用Executors線程執(zhí)行器類創(chuàng)建線程池;

(4)使用ExecutorService執(zhí)行器服務(wù)類的submit()方法將Runnable接口或者Callable接口的實(shí)現(xiàn)類對(duì)象提交到線程池進(jìn)行管理;

(5)線程任務(wù)執(zhí)行完成后,可以使用shutdown()方法關(guān)閉線程池。

接下來通過一個(gè)案例來演示如何通過Executor接口來實(shí)現(xiàn)線程池管理,如例10-18所示。

例10-18 Example18.java

import java.util.concurrent.*;
//1.定義一個(gè)實(shí)現(xiàn)Callable接口的實(shí)現(xiàn)類
class MyThread4 implements Callable<Object>{
    //1.1重寫callable接口的cal1()方法
    public Object call () throwa Exception {
        int i=0;
        while (i++<5)(
            System.out.println(Thread.currentThread().getName()
                               +“的cal1()方法在運(yùn)行“);
        }
        return 1;
     } 
 }
public class Examplel8 {
   public static void main(String[] args) throws InterruptedException,
                                                 ExecutionException (
       //2.創(chuàng)建Callable接口的實(shí)現(xiàn)類對(duì)象
       MyThread4 myThread4 =new MyThread4();
       //3.使用Executors線程執(zhí)行器類創(chuàng)建可擴(kuò)展的線程池
       ExecutorService executor =Executors.newCachedThreadPool () ;
       //4.將cal1able接口實(shí)現(xiàn)類對(duì)象提交到線程池進(jìn)行管理
       Future<Object>resultl=executor.submit(myThread4);
       Future<Object>result2=executor.submit(myThread4);
       //5.關(guān)閉線程池
       executor. shutdown ();
       //對(duì)于有返回值的線程任務(wù),獲取執(zhí)行結(jié)果
       System.out.println("thread-1返回結(jié)果:"+result1.get());
       System.out.println("thread-2返回結(jié)果:"+result2.get());
   }
}

1653041413356_2222.jpg

從圖10-22可以看出,例10-18所示的案例創(chuàng)建了一個(gè)自定義的線程池executor(線程池默認(rèn)生成名稱為pool-1),在該線程池中管理有兩個(gè)默認(rèn)生成名稱的線程thread-1和thread-2,同時(shí)還可以獲取這兩個(gè)線程的執(zhí)行結(jié)果。

在例10-18所示的案例中,線程池是通過Executors的newCachedThreadPool()方法創(chuàng)建的,Executors是JDK5中增加的線程執(zhí)行器工具類,提供了4種方法來創(chuàng)建用于不同需求的線程池,如表10-4所示。

1653041340325_方法聲明.png

分享到:
在線咨詢 我要報(bào)名
和我們?cè)诰€交談!