创建线程池一般有一下几种方法:
ThreadPoolExecutor pool=new ThreadPoolExecutor(5, 5, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); 创建线程池类,自己定义参数
Executors.newFixedThreadPoo()l创建的线程池corePoolSize和maximumPoolSize值是相等的,它使用的LinkedBlockingQueue;
Executors.newSingleThreadExecutor()将corePoolSize和maximumPoolSize都设置为1,也使用的LinkedBlockingQueue;
Executors.newCachedThreadPool()将corePoolSize设置为0,将maximumPoolSize设置为Integer.MAX_VALUE,使用的SynchronousQueue,也就是说来了任务就创建线程运行,当线程空闲超过60秒,就销毁线程。
实际中,如果Executors提供的三个静态方法能满足要求,就尽量使用它提供的三个方法,因为自己去手动配置ThreadPoolExecutor的参数有点麻烦,要根据实际任务的类型和数量来进行配置。
package demo;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
//创建线程池类,自己定义参数
//ThreadPoolExecutor pool=new ThreadPoolExecutor(5, 5, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
//使用静态方法
ThreadPoolExecutor pool=(ThreadPoolExecutor) Executors.newFixedThreadPool(5);//corePoolSize和maxiPoolSize都为5
//ThreadPoolExecutor pool=(ThreadPoolExecutor) Executors.newCachedThreadPool();
//ThreadPoolExecutor pool=(ThreadPoolExecutor) Executors.newSingleThreadExecutor();
for(int i=0;i<5;i++){
Thread thread=new Thread(new MyThread("Thread:"+i));
pool.execute(thread);
}
}
}
class MyThread implements Runnable{
private String threadName;
public MyThread(String name) {
// TODO Auto-generated constructor stub
threadName=name;
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("我是线程:"+threadName);
}
}