线程是同时启动的还是它们之间有延迟?

Are threads started simultaneously or there's delay between them?

比如有一个代码:

ExecutorService exec = Executors.newCachedThreadPool();
for(int i = 0; i < 1000000; i++)
    exec.execute(new SomeRunnable());

语句for执行了1000000次启动线程的操作和运行它的任务。

我们建议同时启动这些线程。好吧,但是如果一个语句 for 一致地、一步一步地执行它们的操作,线程如何同时启动:第一个、第二个、第三个等等?

for(int i=1; i<11; i++) {
    System.out.println("Count is: " + i);
}

// Actions are happened step-by-step, not simultaneosly
/* The output is:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
and so on */

线程依次启动,因为for循环只在一个线程(主线程)中执行,一次执行一条语句。只是速度非常快,所以你可以认为它是同时执行的。

线程一个接一个地启动(非常非常快)。如果他们正在做任何重要的事情,他们将 运行 并行。

来自the documentation of Executors.newCachedThreadPool

Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available. These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks. Calls to execute will reuse previously constructed threads if available. If no existing thread is available, a new thread will be created and added to the pool.

所以你的循环请求执行 10 SomeRunnable 运行nables。池将根据需要创建线程来适应它。它可能最终会创建 10 个线程,或者如果 运行nables 是 令人惊讶的 短暂的,那么在您结束时可能能够重用一些较早的线程你的 for 循环。 (这似乎不太可能,但这是理论上的可能性。)