java線程池代碼樣例 java中線程池

Java實(shí)現(xiàn)通用線程池

線程池通俗的描述就是預(yù)先創(chuàng)建若干空閑線程 等到需要用多線程去處理事務(wù)的時(shí)候去喚醒某些空閑線程執(zhí)行處理任務(wù) 這樣就省去了頻繁創(chuàng)建線程的時(shí)間 因?yàn)轭l 繁創(chuàng)建線程是要耗費(fèi)大量的CPU資源的 如果一個(gè)應(yīng)用程序需要頻繁地處理大量并發(fā)事務(wù) 不斷的創(chuàng)建銷毀線程往往會大大地降低系統(tǒng)的效率 這時(shí)候線程池就派 上用場了

10余年的北塔網(wǎng)站建設(shè)經(jīng)驗(yàn),針對設(shè)計(jì)、前端、開發(fā)、售后、文案、推廣等六對一服務(wù),響應(yīng)快,48小時(shí)及時(shí)工作處理。全網(wǎng)營銷推廣的優(yōu)勢是能夠根據(jù)用戶設(shè)備顯示端的尺寸不同,自動(dòng)調(diào)整北塔建站的顯示方式,使網(wǎng)站能夠適用不同顯示終端,在瀏覽器中調(diào)整網(wǎng)站的寬度,無論在任何一種瀏覽器上瀏覽網(wǎng)站,都能展現(xiàn)優(yōu)雅布局與設(shè)計(jì),從而大程度地提升瀏覽體驗(yàn)。創(chuàng)新互聯(lián)從事“北塔網(wǎng)站設(shè)計(jì)”,“北塔網(wǎng)站推廣”以來,每個(gè)客戶項(xiàng)目都認(rèn)真落實(shí)執(zhí)行。

本文旨在使用Java語言編寫一個(gè)通用的線程池 當(dāng)需要使用線程池處理事務(wù)時(shí) 只需按照指定規(guī)范封裝好事務(wù)處理對象 然后用已有的線程池對象去自動(dòng)選擇空 閑線程自動(dòng)調(diào)用事務(wù)處理對象即可 并實(shí)現(xiàn)線程池的動(dòng)態(tài)修改(修改當(dāng)前線程數(shù) 最大線程數(shù)等) 下面是實(shí)現(xiàn)代碼

//ThreadTask java

package polarman threadpool;

/** *//**

*線程任務(wù)

* @author ryang

*

*/

public interface ThreadTask {

public void run();

}

//PooledThread java

package polarman threadpool;

import java util Collection; import java util Vector;

/** *//**

*接受線程池管理的線程

* @author ryang

*

*/

public class PooledThread extends Thread {

protected Vector tasks = new Vector();

protected boolean running = false;

protected boolean stopped = false;

protected boolean paused = false;

protected boolean killed = false;

private ThreadPool pool;

public PooledThread(ThreadPool pool) { this pool = pool;

}

public void putTask(ThreadTask task) { tasks add(task);

}

public void putTasks(ThreadTask[] tasks) { for(int i= ; itasks length; i++) this tasks add(tasks[i]);

}

public void putTasks(Collection tasks) { this tasks addAll(tasks);

}

protected ThreadTask popTask() { if(tasks size() ) return (ThreadTask)tasks remove( );

else

return null;

}

public boolean isRunning() {

return running;

}

public void stopTasks() {

stopped = true;

}

public void stopTasksSync() {

stopTasks();

while(isRunning()) { try {

sleep( );

} catch (InterruptedException e) {

}

}

}

public void pauseTasks() {

paused = true;

}

public void pauseTasksSync() {

pauseTasks();

while(isRunning()) { try {

sleep( );

} catch (InterruptedException e) {

}

}

}

public void kill() { if(!running)

interrupt();

else

killed = true;

}

public void killSync() {

kill();

while(isAlive()) { try {

sleep( );

} catch (InterruptedException e) {

}

}

}

public synchronized void startTasks() {

running = true;

this notify();

}

public synchronized void run() { try { while(true) { if(!running || tasks size() == ) { pool notifyForIdleThread(); //System out println(Thread currentThread() getId() + : 空閑 ); this wait(); }else {

ThreadTask task;

while((task = popTask()) != null) { task run(); if(stopped) {

stopped = false;

if(tasks size() ) { tasks clear(); System out println(Thread currentThread() getId() + : Tasks are stopped );

break;

}

}

if(paused) {

paused = false;

if(tasks size() ) { System out println(Thread currentThread() getId() + : Tasks are paused );

break;

}

}

}

running = false;

}

if(killed) {

killed = false;

break;

}

}

}catch(InterruptedException e) {

return;

}

//System out println(Thread currentThread() getId() + : Killed );

}

}

//ThreadPool java

package polarman threadpool;

import java util Collection; import java util Iterator; import java util Vector;

/** *//**

*線程池

* @author ryang

*

*/

public class ThreadPool {

protected int maxPoolSize;

protected int initPoolSize;

protected Vector threads = new Vector();

protected boolean initialized = false;

protected boolean hasIdleThread = false;

public ThreadPool(int maxPoolSize int initPoolSize) { this maxPoolSize = maxPoolSize; this initPoolSize = initPoolSize;

}

public void init() {

initialized = true;

for(int i= ; iinitPoolSize; i++) {

PooledThread thread = new PooledThread(this);

thread start(); threads add(thread);

}

//System out println( 線程池初始化結(jié)束 線程數(shù)= + threads size() + 最大線程數(shù)= + maxPoolSize);

}

public void setMaxPoolSize(int maxPoolSize) { //System out println( 重設(shè)最大線程數(shù) 最大線程數(shù)= + maxPoolSize); this maxPoolSize = maxPoolSize;

if(maxPoolSize getPoolSize())

setPoolSize(maxPoolSize);

}

/** *//**

*重設(shè)當(dāng)前線程數(shù)

* 若需殺掉某線程 線程不會立刻殺掉 而會等到線程中的事務(wù)處理完成* 但此方法會立刻從線程池中移除該線程 不會等待事務(wù)處理結(jié)束

* @param size

*/

public void setPoolSize(int size) { if(!initialized) {

initPoolSize = size;

return;

}else if(size getPoolSize()) { for(int i=getPoolSize(); isize imaxPoolSize; i++) {

PooledThread thread = new PooledThread(this);

thread start(); threads add(thread);

}

}else if(size getPoolSize()) { while(getPoolSize() size) { PooledThread th = (PooledThread)threads remove( ); th kill();

}

}

//System out println( 重設(shè)線程數(shù) 線程數(shù)= + threads size());

}

public int getPoolSize() { return threads size();

}

protected void notifyForIdleThread() {

hasIdleThread = true;

}

protected boolean waitForIdleThread() {

hasIdleThread = false;

while(!hasIdleThread getPoolSize() = maxPoolSize) { try { Thread sleep( ); } catch (InterruptedException e) {

return false;

}

}

return true;

}

public synchronized PooledThread getIdleThread() { while(true) { for(Iterator itr=erator(); itr hasNext();) { PooledThread th = (PooledThread)itr next(); if(!th isRunning())

return th;

}

if(getPoolSize() maxPoolSize) {

PooledThread thread = new PooledThread(this);

thread start(); threads add(thread);

return thread;

}

//System out println( 線程池已滿 等待 );

if(waitForIdleThread() == false)

return null;

}

}

public void processTask(ThreadTask task) {

PooledThread th = getIdleThread();

if(th != null) { th putTask(task); th startTasks();

}

}

public void processTasksInSingleThread(ThreadTask[] tasks) {

PooledThread th = getIdleThread();

if(th != null) { th putTasks(tasks); th startTasks();

}

}

public void processTasksInSingleThread(Collection tasks) {

PooledThread th = getIdleThread();

if(th != null) { th putTasks(tasks); th startTasks();

}

}

}

下面是線程池的測試程序

//ThreadPoolTest java

import java io BufferedReader; import java io IOException; import java io InputStreamReader;

import polarman threadpool ThreadPool; import polarman threadpool ThreadTask;

public class ThreadPoolTest {

public static void main(String[] args) { System out println( quit 退出 ); System out println( task A 啟動(dòng)任務(wù)A 時(shí)長為 秒 ); System out println( size 設(shè)置當(dāng)前線程池大小為 ); System out println( max 設(shè)置線程池最大線程數(shù)為 ); System out println();

final ThreadPool pool = new ThreadPool( ); pool init();

Thread cmdThread = new Thread() { public void run() {

BufferedReader reader = new BufferedReader(new InputStreamReader(System in));

while(true) { try { String line = reader readLine(); String words[] = line split( ); if(words[ ] equalsIgnoreCase( quit )) { System exit( ); }else if(words[ ] equalsIgnoreCase( size ) words length = ) { try { int size = Integer parseInt(words[ ]); pool setPoolSize(size); }catch(Exception e) {

}

}else if(words[ ] equalsIgnoreCase( max ) words length = ) { try { int max = Integer parseInt(words[ ]); pool setMaxPoolSize(max); }catch(Exception e) {

}

}else if(words[ ] equalsIgnoreCase( task ) words length = ) { try { int timelen = Integer parseInt(words[ ]); SimpleTask task = new SimpleTask(words[ ] timelen * ); pool processTask(task); }catch(Exception e) {

}

}

} catch (IOException e) { e printStackTrace();

}

}

}

};

cmdThread start();

/**//*

for(int i= ; i ; i++){

SimpleTask task = new SimpleTask( Task + i (i+ )* ); pool processTask(task);

}*/

}

}

class SimpleTask implements ThreadTask {

private String taskName;

private int timeLen;

public SimpleTask(String taskName int timeLen) { this taskName = taskName; this timeLen = timeLen;

}

public void run() { System out println(Thread currentThread() getId() +

: START TASK + taskName + );

try { Thread sleep(timeLen); } catch (InterruptedException e) {

}

System out println(Thread currentThread() getId() +

: END TASK + taskName + );

}

}

使用此線程池相當(dāng)簡單 下面兩行代碼初始化線程池

ThreadPool pool = new ThreadPool( ); pool init();

要處理的任務(wù)實(shí)現(xiàn)ThreadTask 接口即可(如測試代碼里的SimpleTask) 這個(gè)接口只有一個(gè)方法run()

兩行代碼即可調(diào)用

lishixinzhi/Article/program/Java/hx/201311/27203

java中ExecutorService的線程池如何暫停任務(wù)和繼續(xù)任務(wù)? 有這樣的函數(shù)嗎?

接口 java.util.concurrent.ExecutorService 表述了異步執(zhí)行的機(jī)制,并且可以讓任務(wù)在后臺執(zhí)行。一個(gè) ExecutorService 實(shí)例因此特別像一個(gè)線程池。事實(shí)上,在 java.util.concurrent 包中的 ExecutorService 的實(shí)現(xiàn)就是一個(gè)線程池的實(shí)現(xiàn)。

這里有一個(gè)簡單的使用Java 實(shí)現(xiàn)的 ExectorService 樣例:

使用 newFixedThreadPool() 工廠方法創(chuàng)建一個(gè) ExecutorService ,上述代碼創(chuàng)建了一個(gè)可以容納10個(gè)線程任務(wù)的線程池。其次,向 execute() 方法中傳遞一個(gè)異步的 Runnable 接口的實(shí)現(xiàn),這樣做會讓 ExecutorService 中的某個(gè)線程執(zhí)行這個(gè) Runnable 線程。

java線程的經(jīng)典代碼

package threadgroup;

class ThreadDemo3 extends Thread {

private String name;

private int delay;

public ThreadDemo3(String sname, int i_delay) {

name = sname;

delay = i_delay;

}

public void run() {

try {

sleep(delay);

} catch (InterruptedException e) {

}

System.out.println("多線程測試!\n" + name + "\n" + delay);

}

}

public class testMyThread {

public static void main(String[] args) {

ThreadDemo3 th1,th2,th3;

th1 = new ThreadDemo3("線程1", (int) (Math.random() * 900));

th2 = new ThreadDemo3("線程2", (int) (Math.random() * 900));

th3 = new ThreadDemo3("線程3", (int) (Math.random() * 900));

th1.start();

th2.start();

th3.start();

}

}

package threadgroup;

public class threadDemo {

public static void main(String[] args) {

Thread t = Thread.currentThread();

t.setName("你好嗎?");

System.out.println("正在進(jìn)行的Thread是:" + t);

try {

for (int i = 0; i 5; i++) {

System.out.println("我不叫穆繼超" + i);

Thread.sleep(3000);

}

} catch (Exception e) {

// TODO: handle exception

System.out.println("Thread has wrong" + e.getMessage());

}

}

}

package threadgroup;

public class threadDemo2 implements Runnable {

public threadDemo2() {

Thread t1 = Thread.currentThread();

t1.setName("第一個(gè)主進(jìn)程");

System.out.println("正在運(yùn)行" + t1);

Thread t2 = new Thread(this, "");

System.out.println("在創(chuàng)建一個(gè)進(jìn)程");

t2.start();

try {

System.out.println("使他進(jìn)入第一個(gè)睡眠狀態(tài)");

Thread.sleep(2000);

} catch (InterruptedException e) {

System.out.println("Thread has wrong" + e.getMessage());

}

System.out.println("退出第一個(gè)進(jìn)程");

}

public void run() {

try {

for (int i = 0; i 5; i++) {

System.out.println("進(jìn)程" + i);

Thread.sleep(3000);

}

} catch (InterruptedException e) {

// TODO: handle exception

System.out.println("Thread has wrong" + e.getMessage());

}

System.out.println("退出第二個(gè)進(jìn)程");

}

public static void main(String[] args) {

new threadDemo2();

}

}

典型Java線程池的代碼及其各部分功能介紹

( )根據(jù)xml文件來管理線程池的最大最小線程數(shù)( )對線程池通過Timer定期掃描以防止線程未激活 ( )通過某一個(gè)變量(本程序中是freeThreadCount)來得到空閑線程的數(shù)目 一 配置xml(listen xml)是 ?xml version= encoding= UTF ?configConsumeThreadPoolminPools /minPools ! 線程池最小線程 maxPools /maxPools! 線程池最大線程 checkThreadPeriod /checkThreadPeriod ! 檢查線程池中線程的周期 分鐘 /ConsumeThreadPool/config 二 對于ConsumeThreadPoolPara的javabean: import java io *;public class ConsumeThreadPoolPara implements Serializable{private int minPools;private int maxPools;private int checkThreadPeriod;public int getMinPools(){return minPools;}public int getMaxPools(){return maxPools;}public int getCheckThreadPeriod(){return checkThreadPeriod;}public void setMinPools(int minPools){this minPools = minPools;}public void setMaxPools(int maxPools){this maxPools = maxPools;}public void setCheckThreadPeriod(int checkThreadPeriod){this checkThreadPeriod = checkThreadPeriod;}public String toString(){return minPools+ + maxPools+ +checkThreadPeriod;}public ConsumeThreadPoolPara() {}public static void main(String[] args) {ConsumeThreadPoolPara consumeThreadPool = new ConsumeThreadPoolPara();}} 三 解析xml程序代碼(生成ConsumeThreadPoolPara) 使用jdom解析 import jdom *;import jdom input SAXBuilder;import java io *;import java util *;public class ParseConfig {static Hashtable Listens = null;static ConnPara connpara = null;static ConsumeThreadPoolPara consumeThreadPoolPara = null;private static String configxml = listen xml ;static{getConsumeThreadPoolPara(); //得到消費(fèi)的線程池的參數(shù)}/*** 裝載文檔* @return 返回根結(jié)點(diǎn)* @throws JDOMException*/public static Element loadDocument() throws JDOMException{SAXBuilder parser = new SAXBuilder(); // 新建立構(gòu)造器try {Document document = parser build(configxml);Element root = document getRootElement();return root;}catch(JDOMException e){logger error( listen xml文件格式非法! );throw new JDOMException();}}public static ConsumeThreadPoolPara getConsumeThreadPoolPara(){if(consumeThreadPoolPara ==null){try {Element root = loadDocument();Element consumeThreadPool = root getChild( ConsumeThreadPool );if (consumeThreadPool != null) { //代表有數(shù)據(jù)庫配置consumeThreadPoolPara = new ConsumeThreadPoolPara();Element minPools = consumeThreadPool getChild( minPools );consumeThreadPoolPara setMinPools(Integer parseInt(minPools getTextTrim()));Element maxPools = consumeThreadPool getChild( maxPools );consumeThreadPoolPara setMaxPools(Integer parseInt(maxPools getTextTrim()));Element checkThreadPeriod = consumeThreadPool getChild( checkThreadPeriod );consumeThreadPoolPara setCheckThreadPeriod(Integer parseInt(checkThreadPeriod getTextTrim()));}}catch (JDOMException e) {}}return consumeThreadPoolPara;}} 四 線程池源代碼 import java util *;/*** pTitle: 線程池/p* pDescription: 采集消費(fèi)模塊/p* pCopyright: Copyright (c) /p* pCompany: /p* @author 張榮斌* @version */public class ThreadPool {private static int minPools = ; //最小連接池?cái)?shù)目private static int maxPools = ; //最大連接池?cái)?shù)目private static int checkThreadPeriod = ; //檢查連接池的周期ArrayList m_ThreadList; //工作線程列表LinkedList m_RunList = null; //工作任務(wù)列表int totalThread = ; //總線程數(shù)static int freeThreadCount = ; //未被使用的線程數(shù)目private java util Timer timer = null; //定時(shí)器static Object o = new Object();static{ //先初始化線程池的參數(shù)ConsumeThreadPoolPara consumeThreadPoolPara = ParseConfig getConsumeThreadPoolPara();if(consumeThreadPoolPara!=null){minPools = consumeThreadPoolPara getMinPools();maxPools = consumeThreadPoolPara getMaxPools();checkThreadPeriod = consumeThreadPoolPara getCheckThreadPeriod()* * ;}}public void setMinPools(int minPools){this minPools = minPools;}public void setMaxPools(int maxPools){this maxPools = maxPools;}public void setCheckThreadPeriod(int checkThreadPeriod){this checkThreadPeriod = checkThreadPeriod;}public ThreadPool() {m_ThreadList=new ArrayList();m_RunList=new LinkedList();for(int i= ;iminPools;i++){WorkerThread temp=new WorkerThread();totalThread = totalThread + ;m_ThreadList add(temp);temp start();try{Thread sleep( );}catch(Exception e){}}timer = new Timer(true); //啟動(dòng)定時(shí)器timer schedule(new CheckThreadTask(this) checkThreadPeriod);}/*** 當(dāng)有一個(gè)工作來的時(shí)候啟動(dòng)線程池的線程* 當(dāng)空閑線程數(shù)為 的時(shí)候 看總線程是否小于最大線程池的數(shù)目 就new一個(gè)新的線程 否則sleep 直到有空閑線程為止;* 當(dāng)空閑線程不為 則將任務(wù)丟給空閑線程去完成* @param work*/public synchronized void run(String work){if (freeThreadCount == ) {if(totalThreadmaxPools){WorkerThread temp = new WorkerThread();totalThread = totalThread + ;m_ThreadList add(temp);temp start();synchronized(m_RunList){m_RunList add(work);m_RunList notify();}}else{while (freeThreadCount == ) {try {Thread sleep( );}catch (InterruptedException e) {}}synchronized(m_RunList){m_RunList add(work);m_RunList notify();}}} else {synchronized(m_RunList){m_RunList add(work);m_RunList notify();}}}/*** 檢查所有的線程的有效性*/public synchronized void checkAllThreads() {Iterator lThreadIterator = erator();while (lThreadIterator hasNext()) { //逐個(gè)遍厲WorkerThread lTestThread = (WorkerThread) lThreadIterator next();if (! (lTestThread isAlive())) { //如果處在非活動(dòng)狀態(tài)時(shí)lTestThread = new WorkerThread(); //重新生成個(gè)線程lTestThread start(); //啟動(dòng)}}}/*** 打印調(diào)試信息*/public void printDebugInfo(){System out println( totalThread= +totalThread);System out println( m_ThreadList size()= +m_ThreadList size());}/**** pTitle: 工作線程類/p* @author 張榮斌* @version */class WorkerThread extends Thread{boolean running = true;String work;public void run(){while(running){synchronized(o){freeThreadCount++;}synchronized(m_RunList){while(m_RunList size() == ){try{m_RunList wait();if(!running) return;}catch(InterruptedException e){} lishixinzhi/Article/program/Java/gj/201311/27379

分享標(biāo)題:java線程池代碼樣例 java中線程池
當(dāng)前路徑:http://muchs.cn/article22/ddcojjc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站營銷、網(wǎng)站收錄、外貿(mào)建站、建站公司、響應(yīng)式網(wǎng)站、營銷型網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站建設(shè)