我正在使用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