java异步调用工具类_java 异步转同步工具类

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"));

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值