package com.gblfy.threadpool;
public class Reading implements Runnable {
private int count;
private String name;
public Reading(int count, String name) {
this.count = count;
this.name = name;
}
@Override
public void run() {
while (count > 0) {
System.out.println(Thread.currentThread().getName() + "Reading" + name);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
--count;
}
}
}
package com.gblfy.threadpool;
import java.util.concurrent.*;
/**
* 简单实用线程池
*/
public class EasyUseThreadPool {
//固定大小线程池
public static void useFixedThreadPool(int ThreadCount) {
ExecutorService executor = Executors.newFixedThreadPool(ThreadCount);
Runnable runnable01 = new Reading(3, "java 编程思想");
Runnable runnable02 = new Reading(2, "Spring 编程思想");
Runnable runnable03 = new Reading(5, "SpringBoot 编程思想");
Runnable runnable04 = new Reading(3, "SpringCloud 编程思想");
Runnable runnable05 = new Reading(3, "Mysql 编程思想");
executor.execute(runnable01);
executor.execute(runnable02);
executor.execute(runnable03);
executor.execute(runnable04);
executor.execute(runnable05);
//执行完任务后将线程池释放
executor.shutdown();
}
public static void customThtradPool() {
ThreadPoolExecutor custom1 = new ThreadPoolExecutor(
1, 1, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2));
for (int i = 0; i != 5; ++i) {
custom1.execute(new Reading(3, "java 编程思想"));
}
custom1.shutdown();
}
public static void customThtradPool2() {
ThreadPoolExecutor custom2 = new ThreadPoolExecutor(
14, 50, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2), new customRejectHandle());
for (int i = 0; i != 5; ++i) {
custom2.execute(new Reading(3, "java 编程思想"));
}
custom2.shutdown();
}
//自定义拒绝策略
public static class customRejectHandle implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
//拿到阻塞队列,慢慢累加
try {
executor.getQueue().put(r);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
//固定线程池,当线程数量增加内存急剧增加
// useFixedThreadPool(3);
//默认自定义线程池当线程满了,会抛出异常
// customThtradPool();
//升级版本 当队列满了,进入阻塞队列,当线程池空闲了,处理慢慢释放阻塞队列中的任务依次处理
customThtradPool2();
}
}