public void contextInitialized(final ServletContextEvent event) {
try {
System.out.println("start thread");
Thread thread = new Thread(new SerialReader(event, serialPort,mode));
thread.start();
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("thread engaged");
}
即使很难运行此代码也不会出错;“线程接合”从不打印。什么会阻止主线程继续运行?
我已经通过将其替换为
Thread thread = new Thread(new Runnable(){
public void run(){
try {
Thread.sleep(1000);
System.out.println("OUTPUT");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
});
完美无缺。
编辑:构造函数中唯一发生的事情是
private BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
public SerialReader(ServletContextEvent event, String port, int mode) throws Exception {
if (mode==1){
System.out.println("**Mode 1**");
} else {//mode is 1
}
event.getServletContext().setAttribute("serialPortData", queue);
}
edit2:(servlet 上下文监听器)
private static final String SHUTDOWN_REQ = "SHUTDOWN";
public void attributeAdded(ServletContextAttributeEvent event) {
queue = (BlockingQueue<String>) event.getServletContext().getAttribute("serialPortData");
//we always get a null here on first try that's why I added null check
if (queue == null){
System.out.println("Queue is empty");
} else {
String item;
try {
//blocks while queue is empty
while ((item = queue.take()) != SHUTDOWN_REQ) {
System.out.println("*******WEB*******"+item+"*******");
//TODO Broadcast message to connected clients
}
} catch (InterruptedException e) {
System.out.println("queue error");
//e.printStackTrace();
}
}
}