這幾日對接物聯網項目,前端請求資料,後端接口發起TCP請求,由另一個線程來接收資料,這時候需要阻塞前端發起的請求,直到TCP接收資料完畢,再傳回資料給前端。特此寫了一個工具類
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.LockSupport;
public class LockSupportUtil {
//存放線程引用的全局容器
public static final ConcurrentHashMap<Integer, Thread> Thread_Pointer_Map = new ConcurrentHashMap<>();
/**
* 鎖住線程
*
* @param address 存放線程的Key,建議使用System.identityHashCode(Thread.currentThread())來生産Key
* @param thread 線程對象
* @param millisecond 逾時自動釋放線程
* @return
*/
public static void lock(int address, Thread thread, long millisecond) {
//如果位址被占用,則直接釋放掉
Thread thread001 = Thread_Pointer_Map.get(address);
if (thread001 != null) {
LockSupport.unpark(thread001);
Thread_Pointer_Map.remove(address);
}
Thread_Pointer_Map.put(address, thread);
LockSupport.parkUntil(thread, System.currentTimeMillis() + millisecond);
}
/**
* 釋放線程
*
* @param address 線程Key
*/
public static void unlock(int address) {
Thread thread = Thread_Pointer_Map.get(address);
if (thread != null) {
LockSupport.unpark(thread);
Thread_Pointer_Map.remove(address);
}
}
}
使用:發起TCP請求的時候帶上生成的線程Key,也就是address。TCP異步傳回資料的時候帶上這個Key。然後用這個Key去釋放線程。