我怎么控制线程个数呢?
class A extends Thread{
public void run() {
处理代码...........
}
}
--------------------------------------------
class B {
main(){
for(无限循环){
创建A线程并启动线程
}
}
}
------------------------------------------------
我应该怎么控制A的线程个数呢?(当线程数 大于最大数时,for停止,当线程数小于最大数时,for继续创建线程并启动!)
控制是写在A中呢,还是B中呢?
怎么控制呢?
------解决方案--------------------1.4没有直接的类,我一般借用Apache的ObjectPool
import org.apache.commons.pool.PoolableObjectFactory;
import org.apache.commons.pool.impl.GenericObjectPool;
GenericObjectPool pool = new GenericObjectPool();
pool.setFactory(new PoolableObjectFactory() {
public void activateObject(Object arg0) throws Exception {
}
public void destroyObject(Object arg0) throws Exception {
}
public Object makeObject() throws Exception {
return new Object();
}
public void passivateObject(Object arg0) throws Exception {
}
public boolean validateObject(Object arg0) {
return true;
}
});
pool.setMaxActive(1);
for(无限循环){
Object lock = pool.borrowObject();
new A(pool, lock).start();//A在run的finally中执行pool.returnObject(lock);
}
这样就保证最大线程数
------解决方案--------------------我刚才编了一个简单点的方法,测试了一下还可以。楼主要是用JDK1.5,不妨用用里面的线程池来管理,比较方便。下面是我的代码,没有使用线程池,因为不知道楼主的JDK版本。
public class B {
/**
* @param args
*/
public static void main(String[] args) {
int size = 20;
List pool = new ArrayList();
while(true){
if(isPoolFull(pool,size)){
try {Thread.sleep(1);} catch (InterruptedException e) {}
}else{
A a = new A();
pool.add(a);
a.start();
}
}
}
public static boolean isPoolFull(List pool,int poolSize){
int size = pool.size();
for(int i=0;i <size;i++){
A a = (A)pool.get(i);
if(!a.isAlive()){
pool.remove(i);i--;size--;
}
}
if(size> =poolSize)return true;
else return false;
}
}
class A extends Thread {
public void run(){
try {
sleep(5000);
System.out.println(this.getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}