即使从 run() 返回后,启动的线程看起来也没有关闭。在 Netbeans 的左侧面板中,它显示了许多“pool-xx-thread-1-running”的数量,并且每次执行线程时都会增加。下面是我的代码:
//监听操作 client.subscribe("/location/#", new IMqttMessageListener() { public void messageArrived(最终字符串主题,最终MqttMessage消息)抛出异常{ 最终字符串有效负载 = new String(message.getPayload());
System.out.println("Received operation " + payload);
if (payload.startsWith("{\"location\":")) {
// execute the operation in another thread to allow the MQTT client to
// finish processing this message and acknowledge receipt to the server
Executors.newSingleThreadScheduledExecutor().execute(new Runnable() {
public void run() {
if(payload.equals("")) return;
try {
JsonObject jsonObject = new Gson().fromJson(payload, JsonObject.class);
String fixTime="", vehicleid="", deviceTime="", lat="", lon="", speed="",alt="", accuracy="", bearing="";
try{
String locationStr=jsonObject.get("location").toString();
locationStr=locationStr.substring(1, locationStr.length()-1).trim();
locationStr=locationStr.replace("\\", "");
JsonObject locationJson = new Gson().fromJson(locationStr, JsonObject.class);
try{
long millis = Long.parseLong(locationJson.get("mTime").toString());
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(millis);
fixTime = df.format(cal.getTime());
}catch(Exception ex){
}
lat=locationJson.get("mLatitude").toString();
lon=locationJson.get("mLongitude").toString();
alt=locationJson.get("mAltitude").toString();
speed=locationJson.get("mSpeed").toString();
accuracy=locationJson.get("mAccuracy").toString();
bearing=locationJson.get("mBearing").toString();
}catch(Exception ex){
ex.printStackTrace();
}
try{
String entityStr = jsonObject.get("entity").toString();
JsonObject entityJson = new Gson().fromJson(entityStr, JsonObject.class);
vehicleid = entityJson.get("id").toString();
vehicleid = vehicleid.replace("\"", "");
}catch(Exception ex){
ex.printStackTrace();
}
try{
String headerStr=jsonObject.get("header").toString();
JsonObject headerJson = new Gson().fromJson(headerStr, JsonObject.class);
String deviceTimeMsStr = headerJson.get("timestamp").toString();
long msTime = Long.parseLong(deviceTimeMsStr);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(msTime);
deviceTime = df.format(cal.getTime());
}catch(Exception ex){
ex.printStackTrace();
}
Connection conn = null;
Statement stmt = null;
try{
String SQL = "INSERT INTO positions(protocol, deviceid, devicetime, fixtime, valid, latitude, longitude, altitude, speed, course, address, attributes, accuracy, network)";
SQL += " VALUES('osmand',(SELECT id FROM devices WHERE uniqueid = '" + vehicleid + "'),'" + deviceTime + "','" + fixTime + "',1," + lat + "," + lon + "," + alt + "," + speed + "," + bearing + ",'',''," + accuracy + ",'')";
Class.forName("com.mysql.jdbc.Driver");
conn =DriverManager.getConnection(MYSQL_SERVERURL, MYSQL_USERID, MYSQL_PASSWORD);
stmt = conn.createStatement();
stmt.executeUpdate(SQL);
System.out.println("Executed " + SQL);
return;
}catch(Exception ex){
ex.printStackTrace();
}finally {
try {
if(stmt != null)
conn.close();
} catch(SQLException se) {
}
try {
if(conn != null)
conn.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
}catch(Exception ex){
ex.printStackTrace();
}
finally{
return;
}
}
});
}
}
});
最佳答案
我建议您学习 Oracle 的执行器教程。并在 Stack Overflow 上搜索有关此主题的许多现有问题和解答。
仅创建执行器服务一次
不要重复调用Executors.newSingleThreadScheduledExecutor()
。每次调用都会创建一个线程池。你永远不会关闭它们。即使您的应用程序终止,线程也会继续运行。
您应该在应用中仅实例化执行程序服务一次(通常)。然后将返回的 ScheduledExecutorService
对象保存在应用中的某个位置。
当您有一个任务要在后台线程上运行时,检索现有对象并安排该任务。
最终您必须关闭执行程序(及其支持线程池)。
有关更多讨论,请参阅this Answer我的一个非常类似的问题。
ScheduledExecutorService
用于调度
您没有延迟安排任务。所以你不需要 ScheduledExecutorService
。
您只需要一个具有 submit
方法的 ExecutorService
。
关于java - 线程不会自动关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61073347/