2016-10-19 113 views
0

我有一個多線程應用程序。每個線程都應該監聽流數據並處理流中的事件。使用SSE eventSource監聽器喚醒睡眠線程

的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

以下似乎已經做了伎倆..作爲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) { 
    .... 
}