我正在尝试同时运行 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
慕码人8056858
达令说
相关分类