没有找到合适的产品?
联系客服协助选型:023-68661681
提供3000多款全球软件/控件产品
针对软件研发的各个阶段提供专业培训与技术咨询
根据客户需求提供定制化的软件开发服务
全球知名设计软件,显著提升设计质量
打造以经营为中心,实现生产过程透明化管理
帮助企业合理产能分配,提高资源利用率
快速打造数字化生产线,实现全流程追溯
生产过程精准追溯,满足企业合规要求
以六西格玛为理论基础,实现产品质量全数字化管理
通过大屏电子看板,实现车间透明化管理
对设备进行全生命周期管理,提高设备综合利用率
实现设备数据的实时采集与监控
利用数字化技术提升油气勘探的效率和成功率
钻井计划优化、实时监控和风险评估
提供业务洞察与决策支持实现数据驱动决策
原创|其它|编辑:郝浩|2009-10-14 10:54:27.000|阅读 518 次
概述:线程池通俗的描述就是预先创建若干空闲线程,等到需要用多线程去处理事务的时候去唤醒某些空闲线程执行处理任务,这样就省去了频繁创建线程的时间,因为频 繁创建线程是要耗费大量的CPU资源的。
# 界面/图表报表/文档/IDE等千款热门软控件火热销售中 >>
线程池通俗的描述就是预先创建若干空闲线程,等到需要用多线程去处理事务的时候去唤醒某些空闲线程执行处理任务,这样就省去了频繁创建线程的时间,因为频 繁创建线程是要耗费大量的CPU资源的。如果一个应用程序需要频繁地处理大量并发事务,不断的创建销毁线程往往会大大地降低系统的效率,这时候线程池就派 上用场了。
本文旨在使用Java语言编写一个通用的线程池。当需要使用线程池处理事务时,只需按照指定规范封装好事务处理对象,然后用已有的线程池对象去自动选择空 闲线程自动调用事务处理对象即可。并实现线程池的动态修改(修改当前线程数,最大线程数等)。下面是实现代码:
//ThreadTask .java
package polarman.threadpool;
/** *//**
*线程任务
* @author ryang
* 2006-8-8
*/
public interface ThreadTask ...{
public void run();
}
//PooledThread.java
package polarman.threadpool;
import java.util.Collection; import java.util.Vector;
/** *//**
*接受线程池管理的线程
* @author ryang
* 2006-8-8
*/
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=0; i
}
public void putTasks(Collection tasks)...{ this.tasks.addAll(tasks);
}
protected ThreadTask popTask()...{ if(tasks.size() > 0) return (ThreadTask)tasks.remove(0);
else
return null;
}
public boolean isRunning()...{
return running;
}
public void stopTasks()...{
stopped = true;
}
public void stopTasksSync()...{
stopTasks();
while(isRunning())...{ try ...{
sleep(5);
} catch (InterruptedException e) ...{
}
}
}
public void pauseTasks()...{
paused = true;
}
public void pauseTasksSync()...{
pauseTasks();
while(isRunning())...{ try ...{
sleep(5);
} catch (InterruptedException e) ...{
}
}
}
public void kill()...{ if(!running)
interrupt();
else
killed = true;
}
public void killSync()...{
kill();
while(isAlive())...{ try ...{
sleep(5);
} catch (InterruptedException e) ...{
}
}
}
public synchronized void startTasks()...{
running = true;
this.notify();
}
public synchronized void run()...{ try...{ while(true)...{ if(!running || tasks.size() == 0)...{ 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() > 0)...{ tasks.clear(); System.out.println(Thread.currentThread().getId() + ": Tasks are stopped");
break;
}
}
if(paused)...{
paused = false;
if(tasks.size() > 0)...{ 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
* 2006-8-8
*/
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=0; i
PooledThread thread = new PooledThread(this);
thread.start(); threads.add(thread);
}
//System.out.println("线程池初始化结束,线程数=" + threads.size() + " 最大线程数=" + maxPoolSize);
}
public void setMaxPoolSize(int maxPoolSize)...{ //System.out.println("重设最大线程数,最大线程数=" + maxPoolSize); this.maxPoolSize = maxPoolSize;
if(maxPoolSize < getPoolSize())
setPoolSize(maxPoolSize);
}
/** *//**
*重设当前线程数
* 若需杀掉某线程,线程不会立刻杀掉,而会等到线程中的事务处理完成* 但此方法会立刻从线程池中移除该线程,不会等待事务处理结束
* @param size
*/
public void setPoolSize(int size)...{ if(!initialized)...{
initPoolSize = size;
return;
}else if(size > getPoolSize())...{ for(int i=getPoolSize(); i
PooledThread thread = new PooledThread(this);
thread.start(); threads.add(thread);
}
}else if(size < getPoolSize())...{ while(getPoolSize() > size)...{ PooledThread th = (PooledThread)threads.remove(0); th.kill();
}
}
//System.out.println("重设线程数,线程数=" + 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(5); } catch (InterruptedException e) ...{
return false;
}
}
return true;
}
public synchronized PooledThread getIdleThread()...{ while(true)...{ for(Iterator itr=threads.iterator(); 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 10" 启动任务A,时长为10秒"); System.out.println(""size 2" 设置当前线程池大小为2"); System.out.println(""max 3" 设置线程池最大线程数为3"); System.out.println();
final ThreadPool pool = new ThreadPool(3, 2); 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[0].equalsIgnoreCase("quit"))...{ System.exit(0); }else if(words[0].equalsIgnoreCase("size") && words.length >= 2)...{ try...{ int size = Integer.parseInt(words[1]); pool.setPoolSize(size); }catch(Exception e)...{
}
}else if(words[0].equalsIgnoreCase("max") && words.length >= 2)...{ try...{ int max = Integer.parseInt(words[1]); pool.setMaxPoolSize(max); }catch(Exception e)...{
}
}else if(words[0].equalsIgnoreCase("task") && words.length >= 3)...{ try...{ int timelen = Integer.parseInt(words[2]); SimpleTask task = new SimpleTask(words[1], timelen * 1000); pool.processTask(task); }catch(Exception e)...{
}
}
} catch (IOException e) ...{ e.printStackTrace();
}
}
}
};
cmdThread.start();
/**//*
for(int i=0; i<10; i++){
SimpleTask task = new SimpleTask("Task" + i, (i+10)*1000); 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 + """);
}
}
使用此线程池相当简单,下面两行代码初始化线程池:
ThreadPool pool = new ThreadPool(3, 2); pool.init();
要处理的任务实现ThreadTask...接口即可(如测试代码里的SimpleTask),这个接口只有一个方法run()
两行代码即可调用:
ThreadTask task = ... //实例化你的任务对象pool.processTask(task);
本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@evget.com
文章转载自:IT专家网接DevExpress原厂商通知,将于近日上调旗下产品授权价格,现在下单客户可享受优惠报价!
面对“数字中国”建设和中国制造2025战略实施的机遇期,中车信息公司紧跟时代的步伐,以“集约化、专业化、标准化、精益化、一体化、平台化”为工作目标,大力推进信息服务、工业软件等核心产品及业务的发展。在慧都3D解决方案的实施下,清软英泰建成了多模型来源的综合轻量化显示平台、实现文件不失真的百倍压缩比、针对模型中的大模型文件,在展示平台上进行流畅展示,提升工作效率,优化了使用体验。
本站的模型资源均免费下载,登录后即可下载。模型仅供学习交流,勿做商业用途。
本站的模型资源均免费下载,登录后即可下载。模型仅供学习交流,勿做商业用途。
服务电话
重庆/ 023-68661681
华东/ 13452821722
华南/ 18100878085
华北/ 17347785263
客户支持
技术支持咨询服务
服务热线:400-700-1020
邮箱:sales@evget.com
关注我们
地址 : 重庆市九龙坡区火炬大道69号6幢
慧都科技 版权所有 Copyright 2003-
2025 渝ICP备12000582号-13 渝公网安备
50010702500608号