用3个大小的固定线程池去执行6个内部循环3次就结束的任务,为了观察固定线程池下的其他任务一直再等待,希望打印出正在执行的线程名、任务序号和任务内部的循环次数,刚开始看到只有3个线程在执行,并看到任务前仆后继的效果。注意:这10个任务要用各自独立的runnable对象,才能看到任务的序号。
package com.itcast;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPool {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ExecutorService pool = Executors.newFixedThreadPool(3); //建立3个线程池
for(int j=1;j<=6;j++){ //建立6个任务
final int task = j;
pool.execute(new Runnable(){
@Override
public void run() {
for(int i=1;i<=3;i++){ //循环3次
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " loop of " + i + ":" + task);
}
}
});
}
}
}
运行结果为:
pool-1-thread-3 loop of 1:3
pool-1-thread-1 loop of 1:1
pool-1-thread-2 loop of 1:2
pool-1-thread-1 loop of 2:1
pool-1-thread-3 loop of 2:3
pool-1-thread-2 loop of 2:2
pool-1-thread-2 loop of 3:2
pool-1-thread-1 loop of 3:1
pool-1-thread-3 loop of 3:3
pool-1-thread-1 loop of 1:5
pool-1-thread-2 loop of 1:4
pool-1-thread-3 loop of 1:6
pool-1-thread-3 loop of 2:6
pool-1-thread-1 loop of 2:5
pool-1-thread-2 loop of 2:4
pool-1-thread-1 loop of 3:5
pool-1-thread-3 loop of 3:6
pool-1-thread-2 loop of 3:4
pool.shutdownNow() //关闭线程池以外的线程
运行结果为:
pool-1-thread-1 loop of 1:1
pool-1-thread-1 loop of 2:1
pool-1-thread-1 loop of 3:1
pool-1-thread-2 loop of 1:2
pool-1-thread-2 loop of 2:2
pool-1-thread-2 loop of 3:2
pool-1-thread-3 loop of 1:3
pool-1-thread-3 loop of 2:3
pool-1-thread-3 loop of 3:3
发现任务第4到6任务关闭了
改为缓存线程池,可以看到当前有多少个任务,就会分配多少个线程为之服务。
ExecutorService pool = Executors.newCachedThreadPool();
运行结果为
pool-1-thread-1 loop of 1:1
pool-1-thread-1 loop of 2:1
pool-1-thread-1 loop of 3:1
pool-1-thread-2 loop of 1:2
pool-1-thread-2 loop of 2:2
pool-1-thread-2 loop of 3:2
pool-1-thread-4 loop of 1:4
pool-1-thread-4 loop of 2:4
pool-1-thread-4 loop of 3:4
pool-1-thread-3 loop of 1:3
pool-1-thread-3 loop of 2:3
pool-1-thread-3 loop of 3:3
pool-1-thread-5 loop of 1:5
pool-1-thread-5 loop of 2:5
pool-1-thread-5 loop of 3:5
pool-1-thread-6 loop of 1:6
pool-1-thread-6 loop of 2:6
pool-1-thread-6 loop of 3:6
动态分配的线程,有多少个任务就分配多少个线程
总结
在线程池的编程模式下,任务是提交给整个线程池,而不是直接交给某个线程,线程池在拿到任务后,它就在内部找有无空闲的线程,再把任务交给内部某个空闲的线程,这就是封装。记住,任务是提交给整个线程池,一个线程同时只能执行一个任务,但可以同时向一个线程池提交多个任务。