我的每个线程睡眠 2000 毫秒,我有 10 个这样的线程,所以我预计总睡眠时间至少为 20 秒,但它只在 16-18 秒之间出现。抱歉,如果我问的是已经问过的问题。这是我到目前为止所拥有的:
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class MyThreadPoolApp {
public static void main(String[] args) {
long execTime = System.currentTimeMillis();
CountDownLatch latch = new CountDownLatch(1);
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
executor.submit(new Task());
}
System.out.println("threads submitted and waiting execution");
executor.shutdown();
try {
executor.awaitTermination(1, TimeUnit.MINUTES);
} catch (InterruptedException e) {
}
execTime = System.currentTimeMillis() - execTime;
System.out.format("%d threads finished execution \n",Task.getCount());
System.out.println("thread time : " + Task.getTime());
System.out.println("main time : " + execTime);
}
}
任务在哪里:
public class Task implements Runnable {
private static long totalTime;
private static int count;
public static long getTime(){ return totalTime; }
public static int getCount(){ return count; }
public void run() {
count++;
long startTime = System.currentTimeMillis();
try {
Thread.sleep(2000);
totalTime += System.currentTimeMillis() - startTime;
} catch (InterruptedException e) {}
}
}
我的输出:
threads submitted and waiting execution
10 threads finished execution
thread time : 18001
main time : 2020