猿问

Executor 执行两次

我正在尝试同时运行 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


白猪掌柜的
浏览 324回答 3
3回答

慕码人8056858

因为您为构造函数中的每个 Runnables 启动了第二个线程&nbsp;new Thread(this).start();Runnables 是用 ExecutorService 启动的,不需要额外的Thread.start()删除它。

达令说

这是因为你产卵两个线程之外的ExecutorService,并执行你的Runnable那些实施此外也提交他们与你相关的单一线程上执行ExecutorService。删除new Thread(this).start();,您只会看到一次打印输出。但是,由于您使用newFixedThreadPool(1),这实际上意味着您的程序将按顺序运行。
随时随地看视频慕课网APP

相关分类

Java
我要回答