我正在尝试同时运行 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 回答
![?](http://img1.sycdn.imooc.com/5458692c00014e9b02200220-100-100.jpg)
慕码人8056858
TA贡献1803条经验 获得超6个赞
因为您为构造函数中的每个 Runnables 启动了第二个线程 new Thread(this).start();
Runnables 是用 ExecutorService 启动的,不需要额外的Thread.start()
删除它。
![?](http://img1.sycdn.imooc.com/545863e80001889e02200220-100-100.jpg)
达令说
TA贡献1821条经验 获得超6个赞
这是因为你产卵两个线程之外的ExecutorService
,并执行你的Runnable
那些实施此外也提交他们与你相关的单一线程上执行ExecutorService
。
删除new Thread(this).start();
,您只会看到一次打印输出。但是,由于您使用newFixedThreadPool(1)
,这实际上意味着您的程序将按顺序运行。
添加回答
举报
0/150
提交
取消