package com.test.sync;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class Pools {
private static final long timeout = 10000; //ms
private static volatile Map resultMap = new ConcurrentHashMap();
private static volatile Map requestMap = new ConcurrentHashMap();
private static volatile boolean isStart = false;
private static Pools pool = new Pools();
private static Thread mainThread;
private Pools(){
start();
}
public static Pools getInstance(){
return pool;
}
//获取回调值
public boolean callback(String key) {
Boolean result = false;
try {
//放入请求队列
requestMap.put(key, Thread.currentThread());
restart();
//阻塞请求
synchronized (Thread.currentThread()) {
Thread.currentThread().wait(timeout);
}
result = resultMap.get(key) == null ? result : resultMap.get(key);
resultMap.remove(key);
requestMap.remove(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
//将结果加入结果队列
public void put(String key, Boolean value){
resultMap.put(key, value);
restart();
}
private void restart(){
synchronized (mainThread) {
if("WAITING".equalsIgnoreCase(mainThread.getState().name()) && !requestMap.isEmpty()&& !resultMap.isEmpty()){
System.out.println("notify");
mainThread.notify();
}
}
}
//启动循环监听
private synchronized void start(){
if(!isStart){
mainThread = new Thread(new Runnable() {
@Override
public void run() {
while(true){
if(!resultMap.isEmpty() && !requestMap.isEmpty()){
String tmp;
for(Iterator it = requestMap.keySet().iterator(); it.hasNext(); ){
tmp = it.next();
System.out.println("check key-->" + tmp);
if(resultMap.containsKey(tmp)){
Thread t = requestMap.get(tmp);
synchronized(t){
t.notify();
}
}
}
}else{
//如果队列为空,加大间隔
if(!"WAITING".equalsIgnoreCase(mainThread.getState().name())){
try {
synchronized (mainThread) {
mainThread.wait();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
});
mainThread.start();
isStart = true;
System.out.println("-----------start------------");
}
}
public static void main(String[] args) throws Exception {
System.out.println(Pools.getInstance().callback("k2"));
Pools.getInstance().put("k1", false);
Pools.getInstance().put("k2", true);
Pools.getInstance().put("k3", false);
System.out.println(Pools.getInstance().callback("k2"));
}
}