创建Runnable实现类
package ThreadTest;
/**
*
* @author Administrator
*
*/
public class RunnableTest implements Runnable {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName()+"--"+i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"--执行结束");
}
}
再创建测试类,并创建线程池
package ThreadTest;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
public class ThreadPoolTest {
public static void main(String[] args) {
ThreadFactory threadFactory=new ThreadFactoryBuilder().setNameFormat("myThreadPool-%d").build();
LinkedBlockingQueue<Runnable> workQueue=new LinkedBlockingQueue<Runnable>(250);
ExecutorService executor=new ThreadPoolExecutor(3, 5, 20, TimeUnit.SECONDS, workQueue, threadFactory);//创建线程池
for(int i=0;i<10;i++){
RunnableTest test=new RunnableTest();
executor.execute(test);
}
}
}
说明
类和接口
1 ExecutorService 提供线程池操作的接口
提供void execute(Runnable command)方法,传入Runnable的实例即本例中的test;
2 ThreadPoolExecutor ExecutorService的实现类,提供4种构造方法。(只写最后一个)
new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
(1)corePoolSize 核心线程数,即本例中填写的数字3。
(2)workQueue任务队列,负责存放超过核心线程数的请求,可指定大小如本例中LinkedBlockingQueue<Runnable>(250)的250;
(3)maximumPoolSize 创建最大线程数,只有当请求超过任务队列容量和核心线程数量是才会创建,即本例中250+3=253;
(4)handler 当请求超过最大线程数maximumPoolSize和任务队列容量之和时,会调用。(可以查看该RejectedExecutionHandler接口的几个实现类,定义了处理策略,一般默认就行)
(5)keepAliveTime 线程存活时间,对挡前线程多于核心线程数量时会杀死多于的线程保留到核心线程数量。
(6)unit 时间单位
(7)ThreadFactory 线程工厂 用来创建线程的。(采用Google guava来创建的)
运行展示
创建了0,1,2 三个核心线程(当有请求时核心线程才会创建,除非手动设置);
运行过程中可以通过动态更改corePoolSize和maximumPoolSize 的大小,但是只有ThreadPoolExecutor提供了set方法。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。