为了更好地控制多线程,JDK提供了一套线程框架Executor,帮助开发人员有效地进行线程控制,他们都在java.util.concurrent包中,是JDK并发包的核心,其中有一个比较重要的类:Executors,它扮演线程工厂的角色,我们通过这类可以创建特点功能的线程池。
Executors创建线程池方法:
newFixedThreadExecutor()方法,该方法返回一个固定数量的线程池,该方法的线程数始终不变,当有一个任务提交的时候,若线程池中空闲则立即执行,若没有,则会被暂缓在一个任务队列中,等待有空闲的线程去执行。
ExecutorService pool = Executors.newFixedThreadPool(10);
newSingleThreadExecutor()方法,创建一个线程的线程池,若空闲则执行,若没有空闲线程则暂缓在任务队列中。
ExecutorService pool = Executors.newSingleThreadExecutor()
newCachedThreadPool()方法,返回一个可根据实际情况调整线程池个数的线程池,不限制最大的线程数量,若有空闲的线程就执行任务,若无任务则不创建线程,并且每一个空闲的线程会在60S后自动被回收
ExecutorService pool = Executors.newCachedThreadPool();
newScheduledThreadPool()方法,该方法返回一个SchededExecutorService对象,但该线程池可以指定线程数量。(初始化等待2S每隔3S执行一次)
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
class Temp extends Thread
{
public void run()
{
System.out.println("run");
}
}
public class TestTimeJob
{
public static void main(String args[]) throws Exception
{
Temp command = new Temp();
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
ScheduledFuture<?> scheduleTask = scheduler.scheduleWithFixedDelay(command, 2, 3, TimeUnit.SECONDS);
}
}
上面的4中方式,底层都是类似于下面这种方法,都是new ThreadPoolExecutor这样的方式来创建线程池。
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
如果上面4中方式都无法满足我们的业务需求,我们就可以通过new ThreadPoolExecutor来自定义线程池。
1、在使用有界队列时,若有新的任务需要执行,如果线程池实际线程数小于corePoolSize,则优先创建线程,
若大于corePoolSize,则会将任务加入队列,
若队列已满,则在总线程数不大于maximumPoolSize的前提下,创建新的线程,
若线程数大于maximumPoolSize,则执行拒绝策略。或其他自定义方式。
JDK拒绝策略:
AborPolicy:直接抛异常,当系统还能正常工作
CallerRunsPolicy:只要线程池没有关闭,该策略直接在调用者线程中,运行当前被丢弃的任务
DiscardOldestPolicy:丢弃 一个最古老的请求,尝试再次提交当前任务
DiscardPolicy:丢弃无法处理的任务,不给予任何处理。
我们也可以指定自定义的拒绝策略:如下面MyRejected();我们可以在方法内记录一些重要的日志,然后可以跑job。
public class UseThreadPoolExecutor1 {
public static void main(String[] args) {
ThreadPoolExecutor pool = new ThreadPoolExecutor(
1, //coreSize
2, //MaxSize
60, //60
TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(3) //指定一种队列 (有界队列)
//new LinkedBlockingQueue<Runnable>()
, new MyRejected()
//, new DiscardOldestPolicy()
);
MyTask mt1 = new MyTask(1, "任务1");
MyTask mt2 = new MyTask(2, "任务2");
MyTask mt3 = new MyTask(3, "任务3");
MyTask mt4 = new MyTask(4, "任务4");
MyTask mt5 = new MyTask(5, "任务5");
MyTask mt6 = new MyTask(6, "任务6");
pool.execute(mt1);
pool.execute(mt2);
pool.execute(mt3);
pool.execute(mt4);
pool.execute(mt5);
pool.execute(mt6);
pool.shutdown();
}
}
public class MyRejected implements RejectedExecutionHandler{
public MyRejected(){
}
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.out.println("自定义处理..");
System.out.println("当前被拒绝任务为:" + r.toString());
}
}
2、
在使用无界队列时(LinkedBlockingQueue),与有界队列相比,除非系统资源耗尽,否则无界队列不会出现任务入队列失败的情况,当有任务,系统线程数小于corePoolSize,则会将执行该任务。当达到corePoolSize的时候,将不会继续再增加
public class UseThreadPoolExecutor2 implements Runnable{
private static AtomicInteger count = new AtomicInteger(0);
@Override
public void run() {
try {
int temp = count.incrementAndGet();
System.out.println("任务" + temp);
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception{
//System.out.println(Runtime.getRuntime().availableProcessors());
BlockingQueue<Runnable> queue =
//new LinkedBlockingQueue<Runnable>();
new ArrayBlockingQueue<Runnable>(10);
ExecutorService executor = new ThreadPoolExecutor(
5, //core
10, //max
120L, //2fenzhong
TimeUnit.SECONDS,
queue);
for(int i = 0 ; i < 20; i++){
executor.execute(new UseThreadPoolExecutor2());
}
Thread.sleep(1000);
System.out.println("queue size:" + queue.size()); //10
Thread.sleep(2000);
}
}