我有一個非常基本的線程池代碼。 它調用一個位於linkedblockingqueue內的工作對象池。 該代碼通過重新循環工作對象來輸出輸入數據。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日執行 - 在點 電流=(quoteworkerobject)idlechannels.take();
上述有什麼問題?
是否將池的大小從5更改爲20有幫助? – scientiaesthete 2012-08-06 17:13:49
@RanadhirNag投票或接受你喜歡的答案。 ;) – Eugene 2012-08-07 13:40:36