我有一个非常基本的线程池代码。它调用一个位于linkedblockingqueue 中的工作对象池。该代码只是通过重新循环工作对象来打印出输入数据。
我发现以下一致的死锁/冻结:
public class throttleheapthreadpool{
private quoteworkerobject[] channels;
private LinkedBlockingQueue<quoteworkerobject> idlechannels;
public throttleheapthreadpool(int poolsize,int stocks){
channels=new quoteworkerobject[poolsize];
idlechannels=new LinkedBlockingQueue<quoteworkerobject>();
for(int i=1;i<poolsize;i++){
channels[i]=new quoteworkerobject(idlechannels);
idlechannels.add(channels[i]);//All WORKERS to Idle pool to start
}
}
public void execute(Integer quote){
quoteworkerobject current = null;
try {
//extract worker from pool
current = (quoteworkerobject)idlechannels.take();
current.put(quote);
} catch (InterruptedException e) {
}
}
class quoteworkerobject{
LinkedBlockingQueue<Integer> taskqueue=new LinkedBlockingQueue<Integer>();
Thread quotethread=null;
LinkedBlockingQueue<quoteworkerobject> idle=null;
@SuppressWarnings("unchecked")
public quoteworkerobject(LinkedBlockingQueue<quoteworkerobject> idlechannels){
this.idle=idlechannels;
Runnable r=new Runnable(){
public void run() {
insertquote();
}
};
quotethread=new Thread(r);
quotethread.start();//spawn a thread from the worker
}
public void put(Integer quote){
taskqueue.add(quote);
}
public void insertquote(){
try{
Integer thisquote=taskqueue.take();
idle.add(this);
}
catch(Exception ex){
}
}
}
public static void main(String[] args){
throttleheapthreadpool pool=new throttleheapthreadpool(5,200);
Random randomGenerator = new Random();
for(int node=0;node < 20;node++){
int d=randomGenerator.nextInt(5*200);
pool.execute(d);
}
}
}
此代码在第 8 次执行时始终冻结 - 在点 current = (quoteworkerobject)idlechannels.take();
上面有什么问题?