【问题标题】:Start a thread for 5 times at the same time?同时启动一个线程5次?
【发布时间】:2016-02-02 16:47:20
【问题描述】:

我想同时执行一个 cmd 命令五次。所以我创建了一个执行命令的线程并启动了该线程五次。这是正确的吗?

MyRunnable r1 = new MyRunnable();
        ExecutorService executor = Executors.newFixedThreadPool(5);

        for (int i = 0; i < 5; i++) {
            executor.execute(r1);
        }

.......

@Override
    public void run()
    {
        try {
            // Execute command
            String command = "cmd /c start cmd.exe";
            Process child = Runtime.getRuntime().exec(command);

            // Get output stream to write from it
            OutputStream out = child.getOutputStream();

            out.write("cd C:/ /r/n".getBytes());
            out.flush();
            out.write("dir /r/n".getBytes());
            out.close();
        } catch (IOException e) 
        {

        }
    }

【问题讨论】:

  • 你有什么问题?
  • 我不相信。执行时间本身需要时间。如果我没记错的话,启动一个正常的线程大约需要 2 秒
  • 那么线程执行n次的正确方法是什么?
  • @seriously 有用吗?
  • @Kayaman 相反:我没有文件可以保证它。它只是保证它将为我执行代码,但不保证执行方式、顺序等。如果任务非常快,它们可能会在 1 个线程中结束。

标签: java multithreading executorservice


【解决方案1】:

不使用 MyRunnable r1 = new MyRunnable(); 使用 Runnable r1 = new MyRunnable();

要执行线程,我们可以使用 execute() 方法或 submit()。 你的代码对我来说看起来不错。

确保 ExecutorService 已关闭。要关闭 ExecutorService,可以使用 shutdown()\shutdownNow()。 此外,可以使用 awaitTermination() 来等待所有线程终止。

【讨论】:

    【解决方案2】:

    我不太明白,您的问题中的“正确”是什么意思。

    如果你问,这段代码是否有效?那么答案是肯定的。

    这段代码可能会导致一些问题吗?那么答案也是肯定的。

    如果您的可运行对象有一些共同的状态(一些类级别的字段),它们可能会被损坏,因为多个线程将能够修改它。

    如果你的 runnable 是无状态的,并且它的所有变量都在方法范围内声明,那么一切都会好起来的,直到有一天有人会添加一个类级别的变量......并且可能会得到一个非常奇怪的应用程序行为甚至更糟- 一些生产错误,很难找到和调试。为了防止这种行为,您必须为您启动的每个线程创建一个新的可运行类实例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 2017-01-02
      • 1970-01-01
      • 2019-06-21
      • 1970-01-01
      相关资源
      最近更新 更多