【问题标题】:Java program termination in Windows vs Linux console (Ctrl-C not working under windows)Windows 与 Linux 控制台中的 Java 程序终止(Ctrl-C 在 Windows 下不起作用)
【发布时间】:2015-05-06 17:08:42
【问题描述】:

我编写了简单的控制台 Java 程序。它使用ExecutorService,并且运行的线程很少。

我在 Windows 和 Linux 下使用它。

在 Linux 下我可以用 CTRL+C 来终止它,但它在 Windows 下不起作用。

我可以在我的程序中以某种方式“修复”这个问题吗? (无需更改操作系统配置或 Java 运行时配置)。

我正在使用 JDK 1.8 / JRE 1.8。我的代码(删除了“工作”部分):

public class FileProcessor {
    public static void main(String[] args)
    {
        // run 5 threads
        ExecutorService executor = Executors.newFixedThreadPool(5);
        int i;

        // get first and last file ID to process
        int start = Integer.parseInt(args[0]);
        int end = Integer.parseInt(args[1]);

        for (i = start; i < end; i++)
        {
            final int finalId = i; // final necessary in anonymous class
            executor.submit(new Runnable() 
            {
                public void run() 
                {
                    processFile(finalId);
                }
            });
        }

        // I put System.exit(0); here - program will end but threads will still work?
    }

    public static void processFile(int id)
    {
        //doing work here
    }
}

【问题讨论】:

  • 有问题的代码的sn-p会很好

标签: java terminal


【解决方案1】:

在您的 Java 程序中:

  1. 首先通过调用 shutdownNow() 来终止您的 ExecutorService。
  2. 然后就在程序的 main() 方法调用 System.exit(0) 的结束大括号 ("}") 之前;

【讨论】:

  • 但是应该在哪里调用 executor.shutdownNow()?如果工作是在单独的线程中处理的,我猜他们会关闭......
猜你喜欢
  • 1970-01-01
  • 2013-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-17
  • 2013-10-22
  • 1970-01-01
  • 2010-12-18
相关资源
最近更新 更多