手寫簡單執行緒池

2022-09-18 09:36:17 字數 2260 閱讀 9676

執行緒池:

問題:在jdk中什麼代表執行緒池?executor

執行緒池其實就是乙個生產者消費者模型

生產者:提交任務的執行緒

消費者:處理任務的執行緒

產品:任務

問題:大家以前是如何建立執行緒池的?

executors裡面的靜態方法

注意事項:

工作中不要使用executors裡面的靜態方法去建立執行緒裡。

原因:這樣建立的執行緒池,裡面的阻塞佇列都是linkedblockingdeque, 可以』無限』快取任務。

在併發量比較高的場景中,容易導致oom.

最好使用threadpoolexecutor去建立執行緒池

public

class

mythreadpool

implements

executor

public

mythreadpool

(int capacity)

tasks =

newarrayblockingqueue

<

>

(capacity)

;init()

;}private

void

init()

}@override

public

void

execute

(runnable command)

catch

(interruptedexception e)

}private

class

workthread

extends

thread

catch

(interruptedexception e)}}

}}

/*

jdk:blockingqueue|-- arrayblockingqueue: 容量大小固定

|-- linkedblockingdeque: 容量大小步固定,除非指定大小。

*/public

class

myblockingqueue

@suppresswarnings

("unchecked"

)public

myblockingqueue

(int initialcapacity)

elements =

(e)new

object

[initialcapacity];}

public

synchronized

void

enqueue

(e e)

catch

(interruptedexception e1)

}// 新增元素

elements[rear]

= e;

rear =

(rear +1)

% elements.length;

size++

;// 佇列不空, 需要喚醒其它執行緒

notifyall()

;}public

synchronized e dequeue()

catch

(interruptedexception e)

}// 刪除元素

e removevalue = elements[front]

; elements[front]

= null;

front =

(front +1)

% elements.length;

size--

;// 佇列不滿,喚醒其它執行緒

notifyall()

;return removevalue;

}public

synchronized e peek()

catch

(interruptedexception e)

}return elements[front];}

public

synchronized

boolean

isempty()

public

synchronized

intsize()

}

簡單執行緒池類

簡單練習了一下 簡單實現了一下執行緒池類,增加對執行緒的理解和掌控。以後有時間再好好完善下,現在和大家分享下 include include include include include include include include include include include include...

簡單執行緒池實現

執行緒池可以處理多執行緒問題,只要將任務放到任務佇列中,執行緒池中的執行緒就會從佇列中取任務,以預設的優先順序開始執行,如果你的任務數大於正在工作的執行緒數,則執行緒池將會建立一根新的執行緒來輔助工作,但是永遠都不會超過執行緒池中線程的最大值。執行緒池的結構 pragma once include ...

簡單執行緒池實現

1.用於執行大量相對短暫的任務 2.當任務增加的時候能夠動態的增加執行緒池中線程的數量值到達乙個閾值 3.當任務執行完畢的時候,能夠動態的銷毀執行緒池中的執行緒 4.該執行緒池的實現本質上也是生產者與消費者模型的應用。生產者執行緒向任務佇列新增任務,一旦佇列有任務到來,如果有等待 執行緒就喚醒來執行...