是一個(gè)接口,繼承了Executor:
public interface ExecutorService extends Executor {}
而Executor亦是一個(gè)接口,該接口只包含了一個(gè)方法:
void execute(Runnable command);
該類是一個(gè)輔助類,此包中所定義的 Executor、ExecutorService、ScheduledExecutorService、ThreadFactory 和 Callable 類的工廠和實(shí)用方法。
此類支持以下各種方法:
newFixedThreadPool()
創(chuàng)建一個(gè)可重用固定線程數(shù)的線程池,以共享的無界隊(duì)列方式來運(yùn)行這些線程。
void shutdown()
SecurityException
- 如果安全管理器存在并且關(guān)閉,此 ExecutorService 可能操作某些不允許調(diào)用者修改的線程(因?yàn)樗鼪]有保持 RuntimePermission
("modifyThread")),或者安全管理器的 checkAccess 方法拒絕訪問。啟動(dòng)一次順序關(guān)閉,執(zhí)行以前提交的任務(wù),但不接受新任務(wù)。如果已經(jīng)關(guān)閉,則調(diào)用沒有其他作用。
boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException
timeout
- 最長(zhǎng)等待時(shí)間unit
- timeout 參數(shù)的時(shí)間單位InterruptedException
- 如果等待時(shí)發(fā)生中斷請(qǐng)求關(guān)閉、發(fā)生超時(shí)或者當(dāng)前線程中斷,無論哪一個(gè)首先發(fā)生之后,都將導(dǎo)致阻塞,直到所有任務(wù)完成執(zhí)行。既是等待所有子線程執(zhí)行結(jié)束。
void execute(Runnable command)
command
- 可運(yùn)行的任務(wù)RejectedExecutionException
- 如果不能接受執(zhí)行此任務(wù)。NullPointerException
- 如果命令為 null在未來某個(gè)時(shí)間執(zhí)行給定的命令。該命令可能在新的線程、已入池的線程或者正調(diào)用的線程中執(zhí)行,這由 Executor 實(shí)現(xiàn)決定。
Future<?> submit(Runnable task)
task
- 要提交的任務(wù)RejectedExecutionException
- 如果任務(wù)無法安排執(zhí)行NullPointerException
- 如果該任務(wù)為 null提交一個(gè) Runnable 任務(wù)用于執(zhí)行,并返回一個(gè)表示該任務(wù)的 Future。該 Future 的 get 方法在成功 完成時(shí)將會(huì)返回 null。
public class ExecutorServiceTest { public static void main(String[] args) throws IOException, InterruptedException { // 創(chuàng)建一個(gè)固定大小的線程池 ExecutorService service = Executors.newFixedThreadPool(3); for (int i = 0; i < 10; i++) { System.out.println("創(chuàng)建線程" + i); Runnable run = new Runnable() { @Override public void run() { System.out.println("啟動(dòng)線程"); } }; // 在未來某個(gè)時(shí)間執(zhí)行給定的命令 service.execute(run); } // 關(guān)閉啟動(dòng)線程 service.shutdown(); // 等待子線程結(jié)束,再繼續(xù)執(zhí)行下面的代碼 service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); System.out.println("all thread complete"); }}
可以發(fā)現(xiàn)線程被循環(huán)創(chuàng)建,但是啟動(dòng)線程卻不是連續(xù)的,而是由ExecutorService決定的。
聯(lián)系客服