我正在使用ServletContextListener創建一個新線程。從線程讀取數據(在Servlet中)
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.concurrent.*;
public class Port implements ServletContextListener {
private ExecutorService executor;
public void contextDestroyed(ServletContextEvent event) {
executor.shutdown();
}
public void contextInitialized(ServletContextEvent event) {
// start task
executor = Executors.newSingleThreadExecutor();
executor.submit(new Task()); //task should implement Runnable!
}
}
在這個線程裏我正在讀取串口(SerialPortEventListener)的數據。 task.class應該在整個服務器活動期間從串口讀取信息。我已經把它放在一個線程中,因爲只能有一個從串口讀取的實例;數據應該分享給所有客戶。
現在我想訪問這個線程從串口讀取的數據。
可以這樣做嗎?如果是,那麼如何?
你的意思是servlet上下文屬性? – Thomas 2013-03-02 18:03:06
當然可以。感謝您注意到錯字。現在修復。 – 2013-03-02 18:14:01
我真的有很多傳感器數據;你認爲與其他解決方案(回調)相比,這將是有效的嗎? – Thomas 2013-03-02 18:44:05