From d22349714c8d199c02f336f90fba841ef8f5cd39 Mon Sep 17 00:00:00 2001
From: 张世豪 <979909237@qq.com>
Date: 星期五, 21 十一月 2025 17:46:23 +0800
Subject: [PATCH] 优化内存后最终版202511211746

---
 src/chuankou/Sendmsg.java |  157 +++++++++++++++++++++++++++++++++++++++------------
 1 files changed, 119 insertions(+), 38 deletions(-)

diff --git a/src/chuankou/Sendmsg.java b/src/chuankou/Sendmsg.java
index 0b51605..79ace5c 100644
--- a/src/chuankou/Sendmsg.java
+++ b/src/chuankou/Sendmsg.java
@@ -1,6 +1,8 @@
 package chuankou;
 import java.text.SimpleDateFormat;
 import java.util.Date;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicBoolean;
 
 import javax.swing.SwingWorker;
 
@@ -14,35 +16,55 @@
 /**
  * 涓插彛娑堟伅鍙戦�佸伐鍏风被
  * 鎻愪緵楂樻�ц兘鐨勪覆鍙f秷鎭彂閫佸姛鑳斤紝閫傚悎楂橀璋冪敤
+ * 浼樺寲鍐呭瓨浣跨敤锛岄伩鍏嶉暱鏃堕棿杩愯鍐呭瓨娉勬紡
  */
 public class Sendmsg {
     // 闈欐�佷覆鍙f湇鍔″疄渚�
     private static volatile SerialPortService serialService = null;
-    private static volatile boolean isPortOpen = false;
+    private static final AtomicBoolean isPortOpen = new AtomicBoolean(false);
     
     // 鏀逛负闈瀎inal锛屾敮鎸佸姩鎬佹帶鍒�
-    private static boolean DEBUG_MODE = false;
+    private static volatile boolean DEBUG_MODE = false;
     
-    // 鏃ユ湡鏍煎紡鍖�
-    private static final SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss.SSS");
+    // 浣跨敤ThreadLocal淇濊瘉SimpleDateFormat绾跨▼瀹夊叏
+    private static final ThreadLocal<SimpleDateFormat> TIME_FORMATTER = 
+        ThreadLocal.withInitial(() -> new SimpleDateFormat("HH:mm:ss.SSS"));
+    
+    // 缂撳瓨瀛楃涓叉瀯寤哄櫒锛屽噺灏戝璞″垱寤�
+    private static final ThreadLocal<StringBuilder> STRING_BUILDER_CACHE = 
+        ThreadLocal.withInitial(() -> new StringBuilder(128));
+    
+    // 璁板綍娲昏穬鐨凷wingWorker锛屼究浜庣鐞�
+    private static final ConcurrentHashMap<String, SwingWorker<?, ?>> ACTIVE_WORKERS = 
+        new ConcurrentHashMap<>();
    
     
     /**鍙戝崱鏈嶅姟鍣ㄦ帶鍒舵墦寮�鏌愪釜鏌滈棬璋冪敤鎸囦护
      * @param int slotId鏌滈棬缂栧彿1-60
      * @param int type 1鏄湇鍔″櫒鍙戝崱锛�2鏄鐞嗗憳鍙戝崱*/
     public static boolean opendoorzhiling(int slotId,int type) {
-    	lunxun.setSendChaxunzhiling(false);//鏆傚仠鏌ヨ鎸囦护
-    	// 璋冪敤OpenDoor鐢熸垚寮�闂ㄦ寚浠�
-    	String command = OpenDoor.openOneDoor(slotId, type);
-    	boolean sendResult = Sendmsg.sendMessage(command);
-    	String mes=command+";type"+type+"鎺у埗鎵撳紑"+slotId+"鏌滈棬";
-    	Charulog.logOperation(mes);
-    	if (lunxun.DEBUG_ENABLED) {
-            SystemDebugDialog.appendAsciiData(mes);
+        lunxun.setSendChaxunzhiling(false);//鏆傚仠鏌ヨ鎸囦护
+        
+        try {
+            // 璋冪敤OpenDoor鐢熸垚寮�闂ㄦ寚浠�
+            String command = OpenDoor.openOneDoor(slotId, type);
+            boolean sendResult = Sendmsg.sendMessage(command);
+            
+            StringBuilder mesBuilder = STRING_BUILDER_CACHE.get();
+            mesBuilder.setLength(0); // 娓呯┖閲嶇敤
+            mesBuilder.append(command).append(";type").append(type).append("鎺у埗鎵撳紑").append(slotId).append("鏌滈棬");
+            String mes = mesBuilder.toString();
+            
+            Charulog.logOperation(mes);
+            if (lunxun.DEBUG_ENABLED) {
+                SystemDebugDialog.appendAsciiData(mes);
+            }
+            
+            return sendResult;
+        } finally {
+            // 纭繚鎭㈠鏌ヨ鎸囦护
+            lunxun.setSendChaxunzhiling(true);
         }
-    	
-    	lunxun.setSendChaxunzhiling(true);//寮�濮嬫煡璇㈡寚浠�
-		return sendResult;
     }
     
     /**
@@ -50,13 +72,16 @@
      * @param type 鎿嶄綔绫诲瀷锛�1-鏈嶅姟鍣ㄥ彂鍗★紝2-绠$悊鍛樺彂鍗�
      */
     public static void openAllSlots(int type) {
-    	lunxun.setSendChaxunzhiling(false);//鏆傚仠鏌ヨ鎸囦护
+        lunxun.setSendChaxunzhiling(false);//鏆傚仠鏌ヨ鎸囦护
+        
+        String workerKey = "openAllSlots_" + System.currentTimeMillis();
+        
         // 浣跨敤SwingWorker鍦ㄥ悗鍙版墽琛岋紝閬垮厤闃诲UI
         SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
             @Override
             protected Void doInBackground() throws Exception {
                 // 閬嶅巻鎵�鏈夊崱妲斤紙1-60锛�
-                for (int slotId = 1; slotId <= 60; slotId++) {
+                for (int slotId = 1; slotId <= 60 && !isCancelled(); slotId++) {
                     try {
                         // 鐢熸垚寮�闂ㄦ寚浠�
                         String command = OpenDoor.openOneDoor(slotId, type);
@@ -68,12 +93,15 @@
                             Errlog.logOperation("鍙戦�佹寚浠ゅ埌鍗℃Ы " + slotId + " 澶辫触");
                         }
                         
-                        // 闂撮殧100ms
+                        // 闂撮殧100ms锛屼絾妫�鏌ユ槸鍚﹁鍙栨秷
                         Thread.sleep(100);
                         
+                    } catch (InterruptedException e) {
+                        Thread.currentThread().interrupt();
+                        break; // 琚腑鏂椂閫�鍑哄惊鐜�
                     } catch (Exception e) {
                         Errlog.logOperation("澶勭悊鍗℃Ы " + slotId + " 鏃跺彂鐢熼敊璇�: " + e.getMessage());
-                        e.printStackTrace();
+                        // 缁х画澶勭悊涓嬩竴涓崱妲斤紝涓嶄腑鏂惊鐜�
                     }
                 }
                 return null;
@@ -81,22 +109,48 @@
             
             @Override
             protected void done() {
-                // 鍙�夛細瀹屾垚鍚庡彲浠ユ坊鍔犲洖璋冨鐞�
-                System.out.println("鍏ㄩ儴鍗℃Ы寮�闂ㄦ寚浠ゅ彂閫佸畬鎴�");
-                String types="绠$悊鍛�";
-                if(type==1) {
-                	types="鏈嶅姟鍣ㄦ寚浠�";
+                try {
+                    // 娓呯悊worker寮曠敤
+                    ACTIVE_WORKERS.remove(workerKey);
+                    
+                    // 鍙�夛細瀹屾垚鍚庡彲浠ユ坊鍔犲洖璋冨鐞�
+                    if (!isCancelled()) {
+                        StringBuilder messageBuilder = STRING_BUILDER_CACHE.get();
+                        messageBuilder.setLength(0);
+                        
+                        String types = "绠$悊鍛�";
+                        if(type == 1) {
+                            types = "鏈嶅姟鍣ㄦ寚浠�";
+                        }
+                        messageBuilder.append(types).append("宸插皢鍏ㄩ儴鍗℃Ы宸茬粡鎵撳紑璇峰彇鍗�");
+                        String message = messageBuilder.toString();
+                        
+                        Dingshidialog.showTimedDialog(null, 5, message);
+                        Charulog.logOperation(message);
+                    }
+                } finally {
+                    // 纭繚鎭㈠鏌ヨ鎸囦护
+                    lunxun.setSendChaxunzhiling(true);
                 }
-                String message=types+"宸插皢鍏ㄩ儴鍗℃Ы宸茬粡鎵撳紑璇峰彇鍗�";
-                Dingshidialog.showTimedDialog(null,5,message);
-                Charulog.logOperation(message);
             }
         };
         
+        // 璁板綍worker渚夸簬绠$悊
+        ACTIVE_WORKERS.put(workerKey, worker);
         worker.execute();
-        lunxun.setSendChaxunzhiling(true);//寮�濮嬫煡璇㈡寚浠�
     }
     
+    /**
+     * 鍙栨秷鎵�鏈夋鍦ㄦ墽琛岀殑浠诲姟
+     */
+    public static void cancelAllTasks() {
+        ACTIVE_WORKERS.forEach((key, worker) -> {
+            if (!worker.isDone()) {
+                worker.cancel(true);
+            }
+        });
+        ACTIVE_WORKERS.clear();
+    }
     
     /**
      * 璁剧疆涓插彛鏈嶅姟瀹炰緥
@@ -105,7 +159,7 @@
      */
     public static void setSerialService(SerialPortService service, boolean open) {
         serialService = service;
-        isPortOpen = open;
+        isPortOpen.set(open);
     }
     
     /**
@@ -119,7 +173,7 @@
      * 鍙戦�佹秷鎭埌涓插彛锛堝甫閲嶈瘯鏈哄埗锛�
      */
     public static boolean sendMessage(String message) {
-        if (!isPortOpen || serialService == null) {
+        if (!isPortOpen.get() || serialService == null) {
             Errlog.logOperation("[" + getCurrentTime() + "] 涓插彛鏈墦寮�锛屾棤娉曞彂閫佹暟鎹�");
             return false;
         }
@@ -159,17 +213,21 @@
                             break;
                         }
                     } else {
-                        Errlog.logOperation("[" + getCurrentTime() + "] 涓插彛鍙戦�佸け璐ワ紝鎸囦护: " + text.toUpperCase());
-                        Errlog.logOperation("[" + getCurrentTime() + "] 涓插彛鐘舵�� - 鎵撳紑: " + isPortOpen + ", 鏈嶅姟: " + (serialService != null));
-                        if (serialService != null) {
-                            Errlog.logOperation("[" + getCurrentTime() + "] 涓插彛鏈嶅姟鐘舵�� - 鏄惁鎵撳紑: " + serialService.isOpen());
+                        if (DEBUG_MODE) {
+                            Errlog.logOperation("[" + getCurrentTime() + "] 涓插彛鍙戦�佸け璐ワ紝鎸囦护: " + text.toUpperCase());
+                            Errlog.logOperation("[" + getCurrentTime() + "] 涓插彛鐘舵�� - 鎵撳紑: " + isPortOpen.get() + ", 鏈嶅姟: " + (serialService != null));
+                            if (serialService != null) {
+                                Errlog.logOperation("[" + getCurrentTime() + "] 涓插彛鏈嶅姟鐘舵�� - 鏄惁鎵撳紑: " + serialService.isOpen());
+                            }
                         }
                         return false;
                     }
                 }
             } catch (Exception e) {
                 Errlog.logOperation("[" + getCurrentTime() + "] 鍙戦�佸紓甯革紝鎸囦护: " + text.toUpperCase());
-                e.printStackTrace();
+                if (DEBUG_MODE) {
+                    e.printStackTrace();
+                }
                 return false;
             }
         }
@@ -182,7 +240,7 @@
      * @return 涓插彛鎵撳紑鐘舵��
      */
     public static boolean isPortOpen() {
-        boolean open = isPortOpen && serialService != null;
+        boolean open = isPortOpen.get() && serialService != null;
         if (!open && DEBUG_MODE) {
             Errlog.logOperation("[" + getCurrentTime() + "] 涓插彛鐘舵�佹鏌�: 鏈墦寮�");
         }
@@ -229,7 +287,8 @@
             return "";
         }
         
-        StringBuilder sb = new StringBuilder();
+        StringBuilder sb = STRING_BUILDER_CACHE.get();
+        sb.setLength(0);
         for (byte b : bytes) {
             sb.append(String.format("%02x", b));
         }
@@ -241,7 +300,7 @@
      * @return 鏃堕棿瀛楃涓�
      */
     private static String getCurrentTime() {
-        return timeFormat.format(new Date());
+        return TIME_FORMATTER.get().format(new Date());
     }
     
     /**
@@ -267,4 +326,26 @@
         DEBUG_MODE = debug;
         System.out.println("[" + getCurrentTime() + "] Sendmsg璋冭瘯妯″紡: " + (debug ? "鍚敤" : "绂佺敤"));
     }
+    
+    /**
+     * 娓呯悊璧勬簮锛岄槻姝㈠唴瀛樻硠婕�
+     */
+    public static void cleanup() {
+        cancelAllTasks();
+        
+        // 娓呯悊ThreadLocal璧勬簮
+        TIME_FORMATTER.remove();
+        STRING_BUILDER_CACHE.remove();
+        
+        if (DEBUG_MODE) {
+            System.out.println("[" + getCurrentTime() + "] Sendmsg璧勬簮娓呯悊瀹屾垚");
+        }
+    }
+    
+    /**
+     * 鑾峰彇娲昏穬浠诲姟鏁伴噺
+     */
+    public static int getActiveTaskCount() {
+        return ACTIVE_WORKERS.size();
+    }
 }
\ No newline at end of file

--
Gitblit v1.9.3