java归还线程_JAVA线程池线程归还问题

诗芷缘瑶 发布于 2011/06/12 15:01

阅读 1K+

收藏 0

代码如下:

import java.util.LinkedList;

public class ThreadPool {

//线程队列

private LinkedList list = new LinkedList();

//最大线程数

public static final int MAX_THREAD_SIZE = 100;

//最大空闲线程

public static final int MAX_SPACE_SIZE = 50;

//最小空闲线程

public static final int MIN_SPACE_SIZE = 5;

/**

* 初始化线程池

*

*/

public ThreadPool(){

for(int i=0;i

Thread th = new TWork();

th.start();

}

}

/**

* 从线程队列中获得下一个工作线程

* @return

* @throws InterruptedException

*/

public Runnable getNextWorkThread(){

Runnable work = null;

synchronized (list) {

try {

//如果线程队列为空,则等待在使用的工作线程释放

if(list.isEmpty())

list.wait();

work = list.removeLast();//先进先出

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

return work;

}

public void execute(Runnable able){

synchronized (list) {

//添加到任务队列

list.addLast(able);

//唤醒队列中的一个线程

list.notify();

}

}

//工作线程内部类

private class TWork extends Thread{

@Override

public void run() {

Runnable able = getNextWorkThread();

able.run();

//list.addLast(this);

//notify();

}

}

public static void main(String[] args) throws InterruptedException {

ThreadPool pool = new ThreadPool();

for(int i=0;i<20;i++) {

MyThread my = new MyThread();

pool.execute(my);

}

}

}

问题:我初始化的时候只初始化了5个可用的线程连接,在Main里面我需要执行20个任务线程,现在的结果是只会执行5个任务线程就结束了。想请教怎么重复利用线程,即第一个任务线程执行完后把线程连接还给线程池,谢谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值