一、自定义线程池
1、 线程池处理Runnable任务
创建线程池,让线程池创建线程执行任务,使用execute方法
public class ThreadPoolDemon1 {
public static void main(String[] args) {
ExecutorService pool = new ThreadPoolExecutor(3,5,5,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(5),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
//给任务让线程池处理,核心线程3个
pool.execute(new MyRunnable());
pool.execute(new MyRunnable());
pool.execute(new MyRunnable());
//任务队列中排的线程,5个
pool.execute(new MyRunnable());
pool.execute(new MyRunnable());
pool.execute(new MyRunnable());
pool.execute(new MyRunnable());
pool.execute(new MyRunnable());
//创建临时线程,2个
pool.execute(new MyRunnable());
pool.execute(new MyRunnable());
//不创建,触发拒绝策略
pool.execute(new MyRunnable());
}
}
class MyRunnable implements Runnable{
/**
* 2、实现run方法,里面是定义线程以后要干啥(执行任务)
*/
@Override
public void run(){
for (int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName()+"执行输出"+i);
}
try {
System.out.println(Thread.currentThread().getName()+"任务与线程绑定,线程进入休眠");
Thread.sleep(1000000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
输出结果
创建了5个线程,并抛出了异常
2、 线程池处理Callable任务
使用submit方法
public class ThreadPoolDemon2 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService pool = new ThreadPoolExecutor(3,
5,
5,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(5),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
Future<String> futureTask1 = pool.submit(new MyCallable(100));
Future<String> futureTask2 = pool.submit(new MyCallable(200));
Future<String> futureTask3 = pool.submit(new MyCallable(300));
Future<String> futureTask4= pool.submit(new MyCallable(400));
System.out.println(futureTask1.get());
System.out.println(futureTask2.get());
System.out.println(futureTask3.get());
System.out.println(futureTask4.get());
}
}
/**
* 1、定义一个任务类,实现Callable接口 应该申明线程任务执行完毕后的返回结果的数据类型
*/
class MyCallable implements Callable<String>{
private int value;
public MyCallable(int value) {
this.value = value;
}
/**
* @return重写call方法(任务方法),封装要做的事
* @throws Exception
*/
@Override
public String call() throws Exception {
System.out.println(Thread.currentThread().getName()+"开始处理");
int sum=0;
for (int i=0;i<value;i++){
sum+=i;
}
return Thread.currentThread().getName()+"计算0到"+value+"的和为"+sum;
}
}
输出
二、利Executors工具类
Executors工具类通过调用方法返回不同类型的线程池对象
/**
* @author Leah
* @Description:使用Executors的工具方法直接得到一个线程池对象
* @Title: ThreadPoolDemon3
* @Package com.threadPool.ThreadPoolExecutor
* @date 2022-05-13 11:36
*/
public class ThreadPoolDemon3 {
public static void main(String[] args) {
//1、创建固定的线程数据的线程池
try {
ExecutorService pool = Executors.newFixedThreadPool(3);
pool.execute(new MyRunnable());
pool.execute(new MyRunnable());
pool.execute(new MyRunnable());
pool.execute(new MyRunnable());//已经没有多余线程了
} catch (Exception e) {
e.printStackTrace();
}
}
}
不符合阿里巴巴规范