動手實現簡單的執行緒池

2021-08-19 22:37:57 字數 2349 閱讀 3667

廢話不多說,直接開始。

一、屬性變數

執行緒的屬性變數如下

//

執行緒池是否關閉

private boolean

isclosed = false;

//任務佇列

private linkedlistworkqueue;//

執行緒池id

private static int

threadpoolid;//

執行緒id

private int

threadid

;

二、構造方法

public 

threadpool(int size)

}

構造時傳入執行緒數,初始化任務佇列和執行緒

三、操作方法

1、execute方法

public synchronized void 

execute(runnable task) throws exception

execute方法首先判斷判斷執行緒池是否在執行,接著判斷任務是否為空,如果兩個條件都不滿足則將任務加入到任務佇列,然後喚醒執行緒去執行任務

2、gettask方法

public synchronized runnable gettask() throws interruptedexception 

return

workqueue.removefirst();

}

如果任務隊列為空則阻塞當前執行緒,如果執行緒池已關閉則返回null,不然將隊頭返回。

3、join方法

public void 

join()

thread threads = new thread[activecount()];

//enumerate()

方法繼承自

threadgroup

類,獲得執行緒組中當前所有活著的工作執行緒

int count = enumerate(threads);

for (int i=0

; i; i++) catch(interruptedexception ex)

}}

join方法是等待執行緒將工作任務中的任務執行完

4、shutdown方法

public synchronized void 

shutdown()

}

清空任務佇列,中斷所有執行緒

三、工作執行緒類

private class workerthread extends thread

@override

public void

run() catch (exception e)

if (task ==null)

return;

task.run();

} }

}

可以看到,當工作執行緒沒有沒中斷,就去任務佇列取乙個任務執行。

源**如下:繼承執行緒組的好處是執行緒池便於管理執行緒和使用執行緒組的方法

public class threadpool extends threadgroup

}public synchronized void

execute(runnable task) throws exception

public synchronized runnable gettask() throws interruptedexception

return

workqueue.removefirst();

} public void

join()

thread threads = new thread[activecount()];

//enumerate()

方法繼承自

threadgroup

類,獲得執行緒組中當前所有活著的工作執行緒

int count = enumerate(threads);

for (int i=0

; i; i++) catch(interruptedexception ex) }}

public synchronized void

shutdown()

}private class workerthread extends thread

@override

public void

run() catch (exception e)

if (task ==null)

return;

task.run();

} }

}}

自己動手實現自定義執行緒池

老趙在前幾次的post裡分析了.net的自帶執行緒池,由於.net自帶的執行緒池在底層通過win32api呼叫的windows的程序附帶的執行緒池,所以對於程序,這個執行緒池是唯一的,而且很不幸的是很多.net自身的操作也需要通過這個執行緒池來完成,比如timmer。所以我們來嘗試自己寫乙個執行緒池...

c 實現簡單的執行緒池

執行緒池,先建立一定數目的執行緒,初始都處於空閒狀態。當有新的任務進來,從執行緒池中取出乙個空閒的執行緒處理任務,處理完成之後,該執行緒被重新放回到執行緒池中。當執行緒池中的執行緒都在處理任務時,若有新的任務產生,只能等待,直到執行緒池中有執行緒結束任務空閒才能執行。用c 實現固定執行緒數的執行緒池...

c 實現簡單的執行緒池

c 執行緒池,繼承cdoit,實現其中的start和end 標頭檔案 多執行緒管理類 ifndef cthreadpoolmanage h define cthreadpoolmanage h include include include include include include inclu...