1. ThreadPoolExecutor
1: 初始化线程池
ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor(
2,
4,
30,
TimeUnit.SECONDS,
new ArrayBlockingQueue(10),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardPolicy());
2. ScheduledThreadPoolExecutor
1: schedule(new Runnable(),10,TimeUnit.SECONDS),在10S后执行任务,且只执行一次
package com.mxli.concurrent;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPoolDemo {
public static void main(String[] args) {
ScheduledThreadPoolExecutor c=new ScheduledThreadPoolExecutor(2);
ScheduledFuture<?> scheduledFuture = c.schedule(new Runnable() {
@Override
public void run() {
System.out.println("cc");
}
},10, TimeUnit.SECONDS);
}
}
cc
2 scheduleAtFixedRate(new Runnable(),10,60, TimeUnit.SECONDS) 10s后每隔60s执行一次任务
package com.mxli.concurrent;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPoolDemo {
public static void main(String[] args) {
ScheduledThreadPoolExecutor c=new ScheduledThreadPoolExecutor(2);
ScheduledFuture<?> scheduledFuture = c.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("cc");
}
},1,2, TimeUnit.SECONDS);
}
}
cc
cc
cc
.
.
.
3. 关闭线程池操作
1: shutdown()关闭线程池,如果当前有线程池任务未被执行结束、则执行结束后关闭
2: shutdownnow()立即关闭线程池、有任务未被执行完毕,会尝试中断当前线程
一般二者会组合使用
package com.mxli.concurrent;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ShutDown {
private static volatile boolean threadPoolState;
private static volatile ThreadPoolExecutor executor;
public static void main(String[] args) {
if(threadPoolState){
threadPoolState=false;
executor.shutdown();
}
try {
if(executor.awaitTermination(10, TimeUnit.SECONDS)){
executor.shutdownNow();//立即关闭
}
} catch (InterruptedException e) {
e.printStackTrace();
executor.shutdownNow();//如果捕捉到中断信号,则立即关闭,并且中断线程
Thread.currentThread().interrupt();
}
}
}
4. Exectors详解
1: Executors 类提供工厂方法用来创建不同类型的线程池。
2: FixedThreadPool() 指定核心线程数的线程池
ExecutorService c = Executors.newFixedThreadPool(5);
3: SingleThreadExecutor()创建只有一个核心线程数的线程池
ExecutorService c = Executors.newSingleThreadExecutor();
4: CachedThreadPool()