自定义线程池
2018-12-25 本文已影响0人
firststep
自定义线程池的学习:
package StudyOne;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
public class ThreadPoolTest {
public static void main(String[] args) {
//阻塞队列 创建等待队列
BlockingQueue<Runnable> bqr = new ArrayBlockingQueue<Runnable>(20);
//corePoolSize: 核心线程数,默认情况下核心线程会一直存活,即使处于闲置状态也不会受存keepAliveTime限制。除非将allowCoreThreadTimeOut设置为true
// maximumPoolSize: 线程池所能容纳的最大线程数。超过这个数的线程将被阻塞。当任务队列为没有设置大小的LinkedBlockingDeque时,这个值无效
// keepAliveTime: 非核心线程的闲置超时时间,超过这个时间就会被回收
// unit: 指定keepAliveTime的单位,如TimeUnit.SECONDS。当将allowCoreThreadTimeOut设置为true时对corePoolSize生效。
// workQueue: 线程池中的任务队列.常用的有三种队列,SynchronousQueue,LinkedBlockingDeque,ArrayBlockingQueue。
ThreadPoolExecutor pool = new ThreadPoolExecutor(3, 5, 50,TimeUnit.MILLISECONDS, bqr);
Runnable test1 = new MyThead("test1");
Runnable test2 = new MyThead("test2");
Runnable test3 = new MyThead("test3");
Runnable test4 = new MyThead("test4");
Runnable test5 = new MyThead("test5");
Runnable test6 = new MyThead("test6");
pool.execute(test1);
pool.execute(test2);
pool.execute(test3);
pool.execute(test4);
pool.execute(test5);
pool.execute(test6);
}
}
class MyThead implements Runnable {
public String Name;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public MyThead(String name) {
setName(name);
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "正在执行。。。"+getName());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果:
