代码之家  ›  专栏  ›  技术社区  ›  Vertos

即使在Java中断后,线程也会继续打印RAM使用情况

  •  1
  • Vertos  · 技术社区  · 2 年前

    我正在为一个学校项目开发Java程序,在该项目中,我使用独立的线程来监控各种系统资源。然而,我面临的问题是 RAMMonitor 线甚至在呼叫之后 interrupt() 方法,并等待线程加入,它将无限期地继续打印RAM使用情况。

    ---主要代码---

    public class MonitoringResources {
        // Initialize Monitors and Threads //
        private final RAMMonitor monitor_RAM = new RAMMonitor();
        private Thread thread_RAM = new Thread(monitor_RAM);
    
        public MonitoringResources() {}  // Constructor
        
        public void startMonitoring() {  // Start methods
            thread_RAM.start();
        }
        
        public void interruptMonitoring() {  // Interrupt
            thread_RAM.interrupt();
            
            try {  // Wait for the RAM thread to stop
                thread_RAM.join();
            } catch (InterruptedException e) {
            }
        }
        
        public static void main(String[] args) {
            MonitoringResources mr = new MonitoringResources();
            mr.startMonitoring();       // Start monitoring
            
            // Monitoring for 10 seconds //
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
            }
            
            mr.interruptMonitoring();   // Monitor interrupt
            
            System.out.println("Monitoring terminated.");
        }
    }
    

    ---RAM监视器---

    public class RAMMonitor implements Runnable {
        private volatile boolean isRunning = true;
    
        @Override
        public void run() {
            while (isRunning) {
                long usedMemory = getUsedMemory();
                long totalMemory = getTotalMemory();
                double memoryUsage = (double) usedMemory / totalMemory * 100;
    
                System.out.println("RAM Usage -----> " + (int) memoryUsage + "%");
                try {
                    Thread.sleep(1000); // Monitoring per second
                } catch (InterruptedException e) { // Sleep Exception
                    Thread.currentThread().interrupt();
                }
            }
        }
    
        private long getUsedMemory() {
            Runtime runtime = Runtime.getRuntime();
            return runtime.totalMemory() - runtime.freeMemory();
        }
        private long getTotalMemory() {
            Runtime runtime = Runtime.getRuntime();
            return runtime.totalMemory();
        }
        public void interrupt() {
            isRunning = false;
        }
    }
    

    我正在使用 打断 方法来停止线程并等待其加入,然后再结束程序。然而,即使在 打断 呼叫是什么原因导致了这种行为,我如何确保线程按预期停止?

    我曾试图通过将join()调用移到interruptionMonitoring()之外来修改主方法,但问题仍然存在,RAM使用情况继续无限期重复。

    0 回复  |  直到 2 年前