我正在实现一个 Java 数据记录器,它以精确的时间间隔读取来自不同生产机器的一些数据。为了避免一个调用阻塞后续调用,我正在考虑为解析器类的每次调用创建一个新线程。
但是,这需要创建许多线程,然后每 10 秒(这是我的阅读间隔)停止它们。当解析器出现异常(由于我正在使用的物联网设备可能超时)时,非并发方法会导致我出现很多延迟,从而导致下一个调用被延迟。
while(!error){
//JDBC connections and other calls here
//Queryresult is a ResultSet that returns all the machine addresses needing to be read
while(queryresult.next()){
//Parser.ParseSpeedV is the method I need to call concurrently
Double v = Parser.ParseSpeedV(..Params..);
Double s = v*queryresult.getDouble("const");
st = conn.createStatement();
st.executeUpdate("INSERT INTO ...");
}
st.close();
Thread.sleep(10000);
}
实现并发方法调用(方法 ParseSpeedV)而不需要每天启动数千个线程造成的开销的最佳方法是什么?
最佳答案
您要使用的是 ScheduledExecutorService 。它允许您添加以固定速率或固定延迟重复的任务。所以你可以添加一个每 10 秒从设备获取数据的任务。然后,执行器服务确保它在该时间间隔内以相当低的偏差运行。
final ScheduledExecutorService myScheduledExecutor = Executors.newScheduledThreadPool(16);
myScheduledExecutor.scheduleAtFixedRate(myTask, 0L, 10L, TimeUnit.SECONDS);
关于java - Java 数据记录器中频繁的并发方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44921386/