多執行緒實現的幾種方式

2021-10-04 13:52:44 字數 1363 閱讀 4322

public

static

void

main

(string[

] args)

,"thread1").

start()

;}

public

class

calandfuture

catch

(interruptedexception e)}}

class

mytask

implements

callable

}

通過執行緒池建立執行緒

自定義runnable介面,實現run方法,建立執行緒池,呼叫execute方法並傳入物件

優點安全性高,復用執行緒

public

class

pool

executorservice.

shutdown()

;}}class

threaddemo

implements

runnable

}

執行緒池不允許使用 executors去建立,而是通過 threadpool executor的方式,這樣的處理方式讓寫的同學更加明確執行緒池的執行規則,規避資源耗盡的風險

說明1)fixedthreadpool

內部使用linkedblockingqueue, 預設允許的請求佇列長度為 integer. max_value,可能會堆積大量的任務請求,從而導致oom

2)cachedthreadpool

允許的請求佇列長度為 integer. max value,可能會建立大量的執行緒,從而導致oom

threadpoolexecutor executor=

newthreadpoolexecutor(6

,30,0l, timeunit.minutes,

newlinkedblockingdeque

<

>()

);for(

int i =

0; i <

10; i++

) executor.

shutdown()

;

執行緒池詳見執行緒池系列的筆記

list.

parallelstream()

.foreach

(system.out:

:print)

;

多執行緒 實現多執行緒的幾種方式

public class mythread extends thread mythread mythread1 newmythread mythread mythread2 newmythread mythread1.start mythread2.start public class mythre...

多執行緒的幾種實現方式

前面兩種可以歸結為一類 無返回值,原因很簡單,通過重寫run方法,run方式的返回值是void,所以沒有辦法返回結果 後面兩種可以歸結成一類 有返回值,通過callable介面,就要實現call方法,這個方法的返回值是object,所以返回的結果可以放在object物件中 方式1 繼承thread類...

java多執行緒都有幾種方式實現

有三種 1 繼承thread類,重寫run函式 建立 class xx extends thread 開啟執行緒 物件.start 啟動執行緒,run函式執行 2 實現runnable介面,重寫run函式 開啟執行緒 thread t new thread 物件 建立執行緒物件 t.start 3 ...