需求:
两个线程,1个生产者,1个消费者,消费者只消费它想要的数据,并且可以等待指定时间,超过给定时间返回null
使用java自带的阻塞队列,LinkedBlockingQueue,但是不能实现消费者他想要的数据,所以自定义一个实现
下列实现有个不好的地方:生产者生产的数据没有对应消费者,数据就会一直增长,如果不重要的数据可以定时清理
public class InfoChangeCenterManager {
private static final ConcurrentHashMap<String, Object> content=new ConcurrentHashMap<>();
public static boolean putContent(String key,String type,Object value) {
try {
synchronized (content) {
content.put(key+"_"+type, value);
content.notifyAll();
}
return true;
} catch (Exception e) {
return false;
}
}
public static Object getContent(String key,String type,int timeout) {
long start=System.currentTimeMillis();
synchronized (content) {
String keyType=key+"_"+type;
while(!content.containsKey(keyType)){
try {
if((System.currentTimeMillis()-start)>=timeout*1000){//这里一定要写>=,否则可能导致线程一直等待
return null;
}
long time=timeout*1000-(System.currentTimeMillis()-start);
content.wait(time);//这里的时间应该是剩余时间
} catch (Exception e) {
e.printStackTrace();
}
}
return content.remove(keyType);
}
}
}