gpt4 book ai didi

java - 执行器正在执行两次

转载 作者:行者123 更新时间:2023-12-03 12:43:30 25 4
gpt4 key购买 nike

我正在尝试同时运行 2 个线程以实现多线程,并且我的程序正在运行,但我怀疑为什么我的程序会两次打印到标准输出。

这是我的代码库:

public class SimpleExec {
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(5);
CountDownLatch countDownLatch6 = new CountDownLatch(5);
ExecutorService executorService = Executors.newFixedThreadPool(1);
System.out.println("start" + LocalDateTime.now());
executorService.execute(new MyThread("first ", countDownLatch));
executorService.execute(new MyThread("Second", countDownLatch6));

try {
countDownLatch.await();
countDownLatch6.await();
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println("end" + LocalDateTime.now());
executorService.shutdown();

}
}

class MyThread implements Runnable {
String name;
CountDownLatch cdl;

public MyThread(String name, CountDownLatch cdl) {
this.cdl = cdl;
this.name = name;
new Thread(this).start();
}

public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + " " + i);
cdl.countDown();
}
}
}

这是程序输出的示例:

start 2018-08-18T08:41:51.867
first 0 // first time thread labeled 'first' prints 0 through 4
first 1
first 2
first 3
first 4
Second 0
Second 1
Second 2
first 0 // second time thread labeled 'first' prints 0 through 4 - why does it print again here?
first 1
Second 3
first 2
Second 4
first 3
first 4
end2018-08-18T08:41:51.870
Second 0
Second 1
Second 2
Second 3
Second 4

最佳答案

因为您使用 new Thread(this).start();

在构造函数中为每个 Runnable 启动了第二个线程

Runnables 由 ExecutorService 启动,不需要额外的 Thread.start() 只需将其删除。

关于java - 执行器正在执行两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51904936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com