io.github.linmoure.thread.schedule.ThreadSchedule Maven / Gradle / Ivy
package io.github.linmoure.thread.schedule;
import io.github.linmoure.thread.ThreadPoolManager;
import io.github.linmoure.thread.config.SchedulePoolConfig;
import io.github.linmoure.thread.config.ThreadPoolConfig;
import io.github.linmoure.thread.config.ThreadScheduleConfig;
import io.github.linmoure.thread.runnable.LabelRunnable;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import java.util.Queue;
import java.util.concurrent.*;
@Slf4j
public class ThreadSchedule {
private static final String THREAD_NAME = "Thread-Schedule";
public static final Queue BUFFER_QUEUE = new LinkedBlockingQueue<>();
public static ScheduledExecutorService scheduledExecutorService = null;
private final ScheduledFuture> scheduledFuture;
public ThreadSchedule(SchedulePoolConfig schedulePoolConfig) {
// 核心线程数
Integer corePoolSize = schedulePoolConfig.getCorePoolSize() != null ? schedulePoolConfig.getCorePoolSize() : (Runtime.getRuntime().availableProcessors() > 1 ? Runtime.getRuntime().availableProcessors() / 2 : 1);
// 服务启动多长时间启动任务
Integer initialDelay = schedulePoolConfig.getInitialDelay() != null ? schedulePoolConfig.getInitialDelay() : 0;
// 没多少秒执行一次
Integer period = schedulePoolConfig.getPeriod() != null ? schedulePoolConfig.getPeriod() : 2;
scheduledExecutorService = new ScheduledThreadPoolExecutor(schedulePoolConfig.getCorePoolSize(), new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
thread.setName(THREAD_NAME);
return thread;
}
});
scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(new LabelRunnable() {
@Override
public String generateLabel() {
return THREAD_NAME;
}
@Override
public void bnsRun() {
if (log.isDebugEnabled()) {
log.debug("判断缓冲队列是否存在记录size:{}", BUFFER_QUEUE.size());
}
//当线程池的队列容量少于WORK_QUEUE_SIZE,则开始把缓冲队列的任务 加入到 线程池
ThreadSchedule.run();
}
}, initialDelay, period, TimeUnit.SECONDS);
}
private static int run() {
//判断缓冲队列是否存在记录
if (CollectionUtils.isNotEmpty(BUFFER_QUEUE)) {
ThreadScheduleConfig poll = BUFFER_QUEUE.poll();
ThreadPoolConfig config = poll.getConfig();
ThreadPoolExecutor executor = ThreadPoolManager.getExecutor(config.getName());
if (executor.getQueue().size() < poll.getConfig().getQueueCapacity()) {
executor.execute(poll.getRunnable());
return run();
} else {
BUFFER_QUEUE.offer(poll);
return 0;
}
} else {
return 0;
}
}
}