我有一个多线程应用程序。每个线程都应该监听流数据并从流中处理事件。
run()方法目前如下所示:
public void run() {
Client client ClientBuilder.newBuilder().register(SseFeature.class).build();
WebTarget target = client.target("https://stream.example.com/");
org.glassfish.jersey.media.sse.EventSource eventSource =
new org.glassfish.jersey.media.sse.EventSource(target) {
@Override
public void onEvent(InboundEvent inboundEvent) {
System.out.println(inboundEvent.getName()+ " :: " + threadId);
...
}
};
while (true) {
try{
Thread.sleep(500L);
}catch(InterruptedException e){
...
}
}
}
我想要完成的是线程尽可能地休眠,并且只有当事件到达流时才会被唤醒。这样我的大多数线程都可以睡眠并避免CPU负载。我不相信当线程使用Thread.sleep()休眠时,被事件唤醒。毕竟,eventSource侦听器与处于休眠状态的线程相同。
所以我的问题实质上是eventSource是否可以唤醒线程?
答案 0 :(得分:0)
以下似乎已经完成了这个技巧..因为eventInput.read()应该阻止,直到有东西要读。
public void run() {
Client client = ClientBuilder.newBuilder().register(SseFeature.class).build();
WebTarget target = client.target("https://stream.example.com/");
EventInput eventInput = target.request().get(EventInput.class);
while (!eventInput.isClosed()) {
final InboundEvent inboundEvent = eventInput.read();
if (inboundEvent == null) {
// connection has been closed
break;
}
onEvent(inboundEvent);
}
}
protected void onEvent(InboundEvent inboundEvent) {
....
}