Java多執行緒 類Executors主要的工廠方法

2021-06-04 19:13:36 字數 1966 閱讀 4453

executors類,提供了一系列工廠方法用於創先執行緒池,返回的執行緒池都實現了executorservice介面。

1. newfixedthreadpool

public static executorservice newfixedthreadpool(int nthreads);

public static executorservice newfixedthreadpool(int nthreads, threadfactory threadfactory)

建立乙個可重用固定執行緒集合的執行緒池,以共享的無界佇列方式來執行這些執行緒。如果在關閉前的執行期間由於失敗而導致任何執行緒終止,那麼乙個新執行緒將代替它執行後續的任務(如果需要)。

2. newsinglethreadexecutor

public static executorservice newsinglethreadexecutor();

public static executorservice newsinglethreadexecutor(threadfactory threadfactory);

建立乙個使用單個 worker 執行緒的 executor,以無界佇列方式來執行該執行緒。(注意,如果因為在關閉前的執行期間出現失敗而終止了此單個執行緒,那麼如果需要,乙個新執行緒將代替它執行後續的任務)。可保證順序地執行各個任務,並且在任意給定的時間不會有多個執行緒是活動的。與其他等效的 newfixedthreadpool(1) 不同,可保證無需重新配置此方法所返回的執行程式即可使用其他的執行緒。

3. newcachedthreadpool

public static executorservice newcachedthreadpool();

public static executorservice newcachedthreadpool(threadfactory threadfactory);

建立乙個可根據需要建立新執行緒的執行緒池,但是在以前構造的執行緒可用時將重用它們。對於執行很多短期非同步任務的程式而言,這些執行緒池通常可提高程式效能。呼叫 execute 將重用以前構造的執行緒(如果執行緒可用)。如果現有執行緒沒有可用的,則建立乙個新執行緒並新增到池中。終止並從快取中移除那些已有 60 秒鐘未被使用的執行緒。因此,長時間保持空閒的執行緒池不會使用任何資源。注意,可以使用 threadpoolexecutor 構造方法建立具有類似屬性但細節不同(例如超時引數)的執行緒池。

4. newscheduledthreadpool

public static scheduledexecutorservice newscheduledthreadpool(int corepoolsize);

public static scheduledexecutorservice newscheduledthreadpool(int corepoolsize, threadfactory threadfactory);

建立乙個執行緒池,它可安排在給定延遲後執行命令或者定期地執行。

5. newsinglethreadscheduledexecutor

public static scheduledexecutorservice newsinglethreadscheduledexecutor();

public static scheduledexecutorservice newsinglethreadscheduledexecutor(threadfactory threadfactory);

建立乙個單執行緒執行程式,它可安排在給定延遲後執行命令或者定期地執行。(注意,如果因為在關閉前的執行期間出現失敗而終止了此單個執行緒,那麼如果需要,乙個新執行緒會代替它執行後續的任務)。可保證順序地執行各個任務,並且在任意給定的時間不會有多個執行緒是活動的。與其他等效的 newscheduledthreadpool(1) 不同,可保證無需重新配置此方法所返回的執行程式即可使用其他的執行緒。

java多執行緒

在網上看到很有意思的問題,摘下來好好看下 在面試的時候被問了乙個多執行緒的問題 回來仔細思考了一下,多執行緒是否真的能提高了效率?我對多執行緒的理解就是 比如挖乙個隧道,有2種開工方法 1 只在山的一頭挖,直至挖到山的另一頭,從而打通隧道,這可以看成是單執行緒 2 在山的兩頭挖,同時開工,最後在山的...

Java 多執行緒

1。thread類和runnable介面 2。主線程 用thread的static thread currentthread 方法獲得 3。通過實現runnable介面建立執行緒 實現runnable介面的run方法。新執行緒在run 方法返回時結束。注意用這種方法建立程序時,在實現runnable...

JAVA 多執行緒

為hashmap的不正確使用所導致。hashmap在多執行緒環境下使用不安全。使用靜態hashmap作為聯絡人資料快取,key為手機號碼.private static maplxrdata new hashmap 多執行緒環境下不同步hashmap可能導致如下問題 1 多執行緒put操作後可能導致g...