我有三个类,一个代表一堆 url
private Queue<String> queue = new LinkedList<String>();
public Queue<String> getQueue() {
return queue;
}
private int limit = 5;
private int stillParsing;
public synchronized String getNextString() throws InterruptedException {
while (queue.isEmpty()||stillParsing > limit) {
System.out.println("no for you "+ queue.peek());
wait();
}
System.out.println("grabbed");
notify();
stillParsing++;
System.out.println(queue.peek());
return queue.remove();
}
public synchronized void doneParsing() {
stillParsing--;
}
}
一个线程类,其运行方法是
public void run(){
try {
sleep(30);
for(;;){
String currenturl = pile.getNextString();
//(do things)
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
pile.doneParsing();
}
}
还有一个映射器,它使用这个片段实际上将对象添加到一堆 url 中
while (urls.hasMoreTokens()) {
try{
word.set(urls.nextToken());
String currenturl = word.toString();
System.out.println(currenturl);
pile.getQueue().add(currenturl);
从调试中我认为发生的是所有线程都试图在映射器有机会填充它之前立即从队列中获取它并且它们被卡住等待。不幸的是,所有等待的线程都导致我的程序挂起并且没有向队列中添加更多 url。我应该如何处理这个问题?最好在仍然使用等待通知时。