51,411
社区成员
发帖
与我相关
我的任务
分享

public class ThreadTest {
public static void main(String[] args) {
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
fixedThreadPool.submit(() -> {
System.out.println(Thread.currentThread().getName());
});
}
}
}
输出结果
pool-1-thread-1
pool-1-thread-2
pool-1-thread-5
pool-1-thread-4
pool-1-thread-3
pool-1-thread-8
pool-1-thread-9
pool-1-thread-7
pool-1-thread-10
pool-1-thread-6
从输出结果可以看出FixThreadPool每接收一个任务创建一个线程,直到达到核心线程数,只是并发线程执行顺序是不一定的。
for (int i=1;i<10;i++){
int j = i;
pool.execute(()-> {
if (j==5){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"==="+ j);});
}
pool.shutdown();
console:
pool-1-thread-1===1
pool-1-thread-2===2
pool-1-thread-3===3
pool-1-thread-4===4
pool-1-thread-1===6
pool-1-thread-2===7
pool-1-thread-1===9
pool-1-thread-3===8
pool-1-thread-5===5
原来如此