運行后,消費者一直處于waiting狀態(tài),請問該怎么解決我的想法:生產者,因為使用list存放數據,直接添加數據就好;而消費者使用后,再刪除使用數據List licenses = (ArrayList)obj;pool.addLicenses(licenses);消費者線程,其中pool為數據池: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);
}
}以下是數據池,使用list存放數據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();
}}
一個生產者和多個消費者的互斥問題
ibeautiful
2019-03-06 12:11:56