package com.rf.psychological.threadpool;

/**
 * @Author:zzf
 * @Date:2022/6/22:18:22
 * @Description:线程池对象
 */
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.*;

@Slf4j
public class ThreadPool {

    int maximumPoolSize ;
    JSONArray jsonArray ;
    public ThreadPool(int maximumPoolSize,JSONArray jsonArray){
        this.maximumPoolSize = maximumPoolSize;
        this.jsonArray = jsonArray;
    }
    private static ThreadPoolExecutor pool;
    public static void run(int corePoolSize,int maximumPoolSize,JSONArray jsonArray)
    {
        //实现自定义接口
        pool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(5),
                r -> {
                    log.info("线程"+r.hashCode()+"创建");
                    //线程命名
                    return new Thread(r,"threadPool"+r.hashCode());
                }, new ThreadPoolExecutor.CallerRunsPolicy()) {

            protected void beforeExecute(Thread t,Runnable r) {
                log.info("准备执行："+ ((ThreadTask)r).getTaskName());
            }
            protected void afterExecute(Runnable r,Throwable t) {
                log.info("执行完毕："+((ThreadTask)r).getTaskName());
            }
            protected void terminated() {
                log.info("线程池退出");
            }
        };
        List<JSONObject> list = jsonArray.toJavaList(JSONObject.class);
        list.forEach(jsonObject -> {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            pool.execute(new ThreadTask("msg-task-"+jsonObject.getString("phone"),jsonObject));
        });
        pool.shutdown();
    }

}
