事件锁 对象 如果哪个对象 要加锁 执行 take 方法 释放的话 就执行 release 方法 大佬写的 自己 借鉴一下 伪代码如下 不懂就问
/**
* @Description: 事件锁
*/
public class EventLocker {
private int signals = 1;
public synchronized void take() throws InterruptedException {
while (this.signals == 1) {
wait();
}
this.signals--;
this.notify();
}
public synchronized void release() throws InterruptedException {
while (this.signals == 0) {
wait();
}
this.signals++;
this.notify();
}
}
用法简单如下 就是放线程中 等待结果
public void dispatchEvent(BaseEvent event) {
EventHandler handler = observers.getOrDefault(event.getEventType(), null);
log.info("@handler======{}",handler);
if (handler != null) {
//将事件放入活动事件列表
activeEvents.put(event.getSessionId(), event);
log.info("@activeEvents======{}",activeEvents);
//执行事件
this.executorService.execute(() -> {
log.info("11111111======");
boolean ret = handler.handleEvent(event);
log.info("ret======{}",ret);
if (ret) {
try {
log.info("222222222222");
//等待事件执行完成的信号
event.getEventLocker().take();
// ........
log.info("33333333333333");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.info("444444444444444444");
// 执行完成后,从活动事件列表中删除
// activeEvents.remove(event.getClientId());
activeEvents.remove(event.getSessionId());
log.info("555555555555555555555");
});
} else {
log.warn("event not have handler, type: {}, clientId: {}", event.getEventType(), event.getClientId());
}
}
import lombok.Getter;
import java.util.UUID;
@Getter
public class BaseEvent {
private final String sessionId = UUID.randomUUID().toString();
/**
* 客户端ID
*/
private final String clientId;
/**
* 学校ID
*/
private final Long schoolId;
private final EventLocker eventLocker = new EventLocker();
}