package thread;
import java.util.LinkedList;
/**
* 线程池的实现,根据常规线程池的长度,最大长度,队列长度,我们可以增加数目限制实现
* @author Han
*/
public class MyThreadPool extends ThreadGroup{
//cpu 数量 ---Runtime.getRuntime().availableProcessors();
//是否关闭
private boolean isClosed = false;
//队列
private LinkedList<Runnable> workQueue;
//线程池id
private static int threadPoolID;
private int threadID;
public MyThreadPool(int poolSize){
super("MyThreadPool."+threadPoolID);
threadPoolID++;
setDaemon(true);
workQueue = new LinkedList<Runnable>();
for(int i = 0;i<poolSize;i++){
new WorkThread().start();
}
}
//这里可以换成ConcurrentLinkedQueue,就可以避免使用synchronized的效率问题
public synchronized void execute(Runnable task){
if(isClosed){
throw new IllegalStateException("连接池已经关闭...");
}else{
workQueue.add(task);
notify();
}
}
protected synchronized Runnable getTask() throws InterruptedException {
while(workQueue.size() == 0){
if(isClosed){
return null;
}
wait();
}
return workQueue.removeFirst();
}
public synchronized void close(){
if(!isClosed){
isClosed = true;
workQueue.clear();
interrupt();
}
}
public void join(){
synchronized (this) {
isClosed = true;
notifyAll();
}
Thread[] threads = new Thread[activeCount()];
int count = enumerate(threads);
for(int i = 0;i<count;i++){
try {
threads[i].join();
} catch (Exception e) {
}
}
}
class WorkThread extends Thread{
public WorkThread(){
super(MyThreadPool.this,"workThread"+(threadID++));
System.out.println("create...");
}
@Override
public void run() {
while(!isInterrupted()){
System.out.println("run..");
Runnable task = null;
try {
//这是一个阻塞方法
task = getTask();
} catch (Exception e) {
}
if(task != null){
task.run();
}else{
break;
}
}
}
}
}
public class TestMyThreadPool {
public static void main(String[] args) throws InterruptedException {
MyThreadPool pool = new MyThreadPool(3);
for(int i = 0;i<10;i++){
pool.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println("working...");
}
});
}
pool.join();
//pool.close();
}
}
<bean id="executorService" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="${threadpool.corePoolSize}" />
<!-- 线程池维护线程的最少数量 -->
<property name="keepAliveSeconds" value="${threadpool.keepAliveSeconds}" />
<!-- 线程池维护线程所允许的空闲时间 -->
<property name="maxPoolSize" value="${threadpool.maxPoolSize}" />
<!-- 线程池维护线程的最大数量 -->
<property name="queueCapacity" value="${threadpool.queueCapacity}" />
<!-- 线程池所使用的缓冲队列 -->
</bean>
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有