SpringBoot 執行緒池(一) 使用同步執行緒池

2022-07-10 18:48:09 字數 2302 閱讀 7217

建立同步任務類synctask,新增@component注釋

為了測試方便,只列印一行資訊

/**

* 同步任務

*/public void sync() catch (interruptedexception e)

}

/** 同步任務執行緒池 */

private final executorservice executorservice = new threadpoolexecutor(10, 20, 60l,

timeunit.milliseconds, new linkedblockingqueue<>(50),

new threadfactorybuilder().setnameformat("sync-task-thread-pool-%d").build());

/** * 執行方法

*/public void execute()

@component

public class synctask catch (interruptedexception e)

}/**

* 執行方法

*/public void execute()

}

本次使用junit5進行測試,完整**如下:

@springboottest

@autowired

synctask synctask;

@test

public void syncwithoutthreadpool()

long endtime = system.currenttimemillis();

system.out.println("total time:" + (endtime - starttime));

}}

列印日誌結果:

start execute task...

main:sync execute task...

main:sync execute task...

main:sync execute task...

main:sync execute task...

main:sync execute task...

main:sync execute task...

main:sync execute task...

main:sync execute task...

main:sync execute task...

main:sync execute task...

total time:10117

@springboottest

@autowired

synctask synctask;

@test

public void syncwiththreadpool()

long endtime = system.currenttimemillis();

system.out.println("total time:" + (endtime - starttime));

}}

列印日誌結果:

start execute task...

sync-task-thread-pool-0:sync execute task...

sync-task-thread-pool-1:sync execute task...

sync-task-thread-pool-2:sync execute task...

sync-task-thread-pool-3:sync execute task...

sync-task-thread-pool-4:sync execute task...

sync-task-thread-pool-5:sync execute task...

sync-task-thread-pool-6:sync execute task...

sync-task-thread-pool-7:sync execute task...

sync-task-thread-pool-8:sync execute task...

total time:2

sync-task-thread-pool-9:sync execute task...

由上述結果可見:使用執行緒池執行批量任務速度要快。

springBoot執行緒池

1 定義執行緒池 enableasync configuration classtaskpoolconfig 上面我們通過使用threadpooltaskexecutor建立了乙個執行緒池,同時設定了以下這些引數 說明 setwaitfortaskstocompleteonshutdown true...

Springboot 執行緒池

配置類 configuration enableasync public class taskpoolconfig 執行執行緒中,如果有區域性變數要使用 或者有外部值傳入 新建thead 實現callable介面 可以直接使用函式中的值的話使用lambda表示式,使用completionservic...

springboot 執行緒池

1 在啟動類上加標記 enableasync slf4j exclude enableasync public class extends springbootservletinitializer 3 使用,方法名上加 async asyncserviceexecutor 這個方法只在外部呼叫才會開...