运行后,消费者一直处于waiting状态,请问该怎么解决
我的想法:
生产者,因为使用list存放数据,直接添加数据就好;而消费者使用后,再删除使用数据
[code="java"]List licenses = (ArrayList)obj;
pool.addLicenses(licenses);[/code]
消费者线程,其中pool为数据池:
[code="java"]
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:SS");
TimeZone t = sdf.getTimeZone();
t.setRawOffset(0);
sdf.setTimeZone(t);
synchronized(pool) {
while (true) {
String license = pool.getLicense();
System.out.println("Get "+license);
}
}
[/code]
以下是数据池,使用list存放数据
[code="java"]package com.traffic.cache;
import java.util.ArrayList;
import java.util.List;
public class LicensePool {
private List<String> licenses = new ArrayList<String>();
public LicensePool() {
}
public synchronized void addLicenses(List<String> license) {
licenses.addAll(license);
notifyAll();
}
public synchronized String getLicense(){
while(!haveLicense()) {
try {
System.out.println("Waiting");
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String l = licenses.get(0);
System.out.println(l);
licenses.remove(0);
return l;
}
public boolean haveLicense() {
if(licenses.isEmpty()){
return false;
}
return true;
}
public int getSize() {
return licenses.size();
}
}
[/code]