自定义线程池类,使用阻塞原理,多的任务等待
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class MyThreadPool {
private ThreadPoolExecutor pool;
//初始化线程池参数
public MyThreadPool(int numberPools, int readyNumber) {//线程池总数,初始化数
pool = new ThreadPoolExecutor(
numberPools,
numberPools, 1,
TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(readyNumber),
new CustomThreadFactory(),
new ProcessingStrategy());
}
//关闭线程池,如果线程池中有任务,任务会丢失
public void destory() {
if (pool != null) {
pool.shutdownNow();
}
}
//缓冲方式
private class CustomThreadFactory implements ThreadFactory {
private AtomicInteger count = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
String threadName = MyThreadPool.class.getSimpleName() + count.addAndGet(1);
t.setName(threadName);
return t;
}
}
//任务添加到线程池的方式,处理策略
private class ProcessingStrategy implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
executor.getQueue().put(r);// 核心改造点,offer改成put阻塞方法
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//传递任务方法
public void execute(Runnable runnable) {
this.pool.execute(runnable);
}
//监控方法
public void getMessage() {
int poolSize = pool.getPoolSize();
int size = pool.getQueue().size();
long count = pool.getCompletedTaskCount();
int active = pool.getActiveCount();
System.out.println(String.format("线程池中线程数目:%d,队列中等待执行的任务数目:%d,已执行玩别的任务数目:%d, 活跃的线程数: %d", poolSize, size, count, active));
}
}
测试类
MyThreadPool pool = new MyThreadPool(40,20);//创建类
pool.execute(new Runnable(){...});//传任务
附:主线程等待子线程代码
final CountDownLatch latch = new CountDownLatch(5);//设置线程数量
new Thread(new Runnable() {
@Override
public void run() {
latch.countDown();
System.out.println("线程");
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
System.out.println("主线程");
线程停止
main(){
Thread main = Thread.currentThread();
System.out.println(main.getName());
main.interrupt();
System.out.println("main线程已经退出了,但是不影响其他线程运行!");
}