
[英]Writing to a non-blocking NIO UDP (DatagramChannel) socket after processing request on a separate thread
[英]After getting socket data call separate thread for further processing?
当前,我有此套接字程序,该程序将从设备中接收数据,然后执行冗长的过程,例如检查地理围栏和其他相关逻辑,最后将数据保存到db中。 以下是我的代码的外观
这是启动套接字的代码public static void main(String [] args){
new commS();
}
commS() {
try {
// setup the connection pool
HikariConfig config = new HikariConfig ();
config.setJdbcUrl("jdbc:mysql://localhost:3306/****");
config.setUsername("*****");
config.setPassword("*****");
config.setMaximumPoolSize(20);
//config.setPartitionCount(1);
connectionPool = new HikariDataSource(config); // setup the connection pool
}
catch (Exception e) {
e.printStackTrace(System.out);
}
try
{
final ServerSocket serverSocketConn = new ServerSocket(8000);
while (true)
{
try
{
Socket socketConn1 = serverSocketConn.accept();
new Thread(new ConnectionHandler(socketConn1)).start();
}
catch(Exception e)
{
System.out.println("MyError:Socket Accepting has been caught in main loop."+e.toString());
e.printStackTrace(System.out);
}
}
}
catch (Exception e)
{
System.out.println("MyError:Socket Conn has been caught in main loop."+e.toString());
e.printStackTrace(System.out);
//System.exit(0);
}
这是完成连接处理程序的其余套接字连接代码。
class ConnectionHandler implements Runnable {
private Socket receivedSocketConn1;
ConnectionHandler(Socket receivedSocketConn1) {
this.receivedSocketConn1=receivedSocketConn1;
}
public void run() { // etc
w = null;
BufferedReader r = null;
String message="";
try {
/// here I read for the data and call the rest of the function etc.
I would like to split into separate thread?
}
catch (SocketTimeoutException ex)
{
System.out.println("MyError:SocketTimeoutException has been caught in in the main first try");
ex.printStackTrace();
}
catch (IOException ex)
{
System.out.println("MyError:IOException has been caught in in the main first try");
ex.printStackTrace();
}
}
我已经标记了///,在这里我读取了数据并调用了函数的其余部分。在该运行函数中,我接收了数据,验证并调用了所有其他函数,最后将数据保存到db中。 我觉得这是一个漫长的过程。 我想将其分为两部分,只是为了读取数据,然后将此数据字符串传递给单独的线程,所以下面的内容是我想要实现的。
因此,在运行功能中,我计划执行此操作Thread t = new Thread(new MyRProcessing(parameter)); t.start(); 我不太确定这是正确的吗? 我应该将MyRProcessing编写为单独的.java还是全部放入一个Java中?
public class MyRProcessing implements Runnable {
private X parameter;
public MyRProcessing (X parameter) {
this.parameter = parameter;
}
public void run() {
}
}
您可以在此处找到生产者-消费者的示例
这涉及多线程和同步的一般问题,我强烈建议在继续之前先阅读这些内容。
提出建议的最简单方法是简单地扩展Thread类并通过构造函数传递数据,然后在run()
方法中对其进行处理。 在大多数情况下,这不是最好的方法,但这很简单。
例如
public class MyThread extends Thread {
private String data;
public MyThread(String data) {
this.data = data;
}
public void run() { /* process data */ }
}
然后只需启动线程,完成后它将返回并且线程将终止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.