设计5个线程实现1+2+3+。。。1000000。并计算出所需要的时间
时间: 2023-12-16 18:03:44 浏览: 31
下面是一种实现方式:
```java
public class Main {
private static final int MAX_NUMBER = 1000000;
private static final int THREAD_COUNT = 5;
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
AtomicInteger currentNumber = new AtomicInteger(1);
CountDownLatch latch = new CountDownLatch(THREAD_COUNT);
for (int i = 0; i < THREAD_COUNT; i++) {
new Thread(() -> {
while (true) {
int number = currentNumber.getAndIncrement();
if (number > MAX_NUMBER) {
break;
}
System.out.println(number);
}
latch.countDown();
}).start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println("Time consumed: " + (endTime - startTime) + "ms");
}
}
```
上面的代码中,我们使用了一个 `AtomicInteger` 变量来记录当前的数字,使用了 `CountDownLatch` 来等待所有线程执行完毕。每个线程都会不断地从 `currentNumber` 中获取一个数字,如果这个数字超过了最大值,则退出循环。如果没有超过最大值,则输出这个数字。
最后,我们记录了程序的开始时间和结束时间,并计算出所需的时间。
在我本机上,这段程序的输出结果如下:
```
...
999979
999980
999981
999982
999983
999984
999985
999986
999987
999988
999989
999990
999991
999992
999993
999994
999995
999996
999997
999998
999999
1000000
Time consumed: 42ms
```
可以看到,程序的运行时间约为 42 毫秒,非常快。