为了账号安全,请及时绑定邮箱和手机立即绑定

Executor 执行两次

Executor 执行两次

白猪掌柜的 2021-07-20 20:49:57
我正在尝试同时运行 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.867first  0 // first time thread labeled 'first' prints 0 through 4first  1first  2first  3first  4Second 0Second 1Second 2first  0   // second time thread labeled 'first' prints 0 through 4 - why does it print again here?first  1Second 3first  2Second 4first  3first  4end2018-08-18T08:41:51.870Second 0Second 1Second 2Second 3Second 4
查看完整描述

3 回答

?
慕码人8056858

TA贡献1803条经验 获得超6个赞

因为您为构造函数中的每个 Runnables 启动了第二个线程 new Thread(this).start();

Runnables 是用 ExecutorService 启动的,不需要额外的Thread.start()删除它。


查看完整回答
反对 回复 2021-07-29
?
达令说

TA贡献1821条经验 获得超6个赞

这是因为你产卵两个线程之外ExecutorService,并执行你的Runnable那些实施此外也提交他们与你相关的单一线程上执行ExecutorService

删除new Thread(this).start();,您只会看到一次打印输出。但是,由于您使用newFixedThreadPool(1),这实际上意味着您的程序将按顺序运行。


查看完整回答
反对 回复 2021-07-29
  • 3 回答
  • 0 关注
  • 323 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信