简体   繁体   English

从线程中读取数据(在Servlet中)

[英]Reading data from a thread ( in a Servlet)

I'm using the ServletContextListener to create a new thread. 我正在使用ServletContextListener来创建一个新线程。

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!

        }
    }

Inside this thread I'm reading data from a serial port (SerialPortEventListener). 在这个线程中,我正在从串口(SerialPortEventListener)读取数据。 The task.class should read out information from the serial port during the whole period in which the server is active. task.class应该在服务器处于活动状态的整个期间从串口读出信息。 I've thrown this inside a thread because there can only be one instance that reads from the serial port; 我把它扔进了一个线程,因为只能有一个实例从串口读取; data should then be shared to all clients. 然后应该将数据共享给所有客户端。

Now I would like to acces the data this thread is reading from the serial port. 现在我想访问此线程从串行端口读取的数据。

Can this be done? 可以这样做吗? And if yes then how? 如果是,那怎么样?

You could, for example, store the read data in a servlet context attribute. 例如,您可以将读取的数据存储在servlet上下文属性中。 Then, from the other classes, you would get the attribute from the servlet context: 然后,从其他类中,您将从servlet上下文中获取该属性:

public void contextInitialized(final ServletContextEvent event) { 
        // start task
        executor = Executors.newSingleThreadExecutor();
        executor.submit(new Runnable() {
            @Override
            public void run() {
                String data = readFromPort();
                event.getServletContext().setAttribute("serialPortData", data); 
            }
        });
    }
}

Yes it can be done, and you have few options: 是的,它可以完成,你几乎没有选择:

1- Using a shared concurrent.BlockingQueue where inside the thread add new data from the SerialPort and in your servlet read from that queue 1-使用共享的concurrent.BlockingQueue ,其中在线程内部从SerialPort添加新数据并在servlet中从该队列中读取

2- Have an event listener object inside your servlet and pass it in your task constructor. 2-在servlet中有一个事件监听器对象,并在task构造函数中传递它。 The listener object should have a callback function that is invoked when SerialEvent occur. 侦听器对象应具有在发生SerialEvent时调用的回调函数。

In general, this is a typical producer/consumer pattern 通常,这是典型的生产者/消费者模式

You'll need to share the data in the new Runnable you're going to create. 您需要在要创建的新Runnable中共享数据。 You can add to it a concurrent collection . 您可以向其添加并发集合

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM