package com.dy.common.mw.core;
|
|
import org.apache.logging.log4j.*;
|
|
import com.dy.common.queue.Queue;
|
|
public class CoreThread extends Thread{
|
|
private static Logger log = LogManager.getLogger(CoreThread.class.getName()) ;
|
|
private static CoreThread instance = new CoreThread() ;
|
|
private static Long sleepBigBusy = 100L ;//大忙时(除了恒久任务,还有其他任务),核心线程暂停间隔
|
private static Long sleepSmallBusy = 500L ;//小忙时(只有恒久任务,无其他任务),核心线程暂停间隔
|
|
private CoreThread(){
|
}
|
|
public static CoreThread getInstance(){
|
return instance ;
|
}
|
|
/**
|
* 设置暂停时长
|
* @param sleepBigBusy 大忙时(除了恒久任务,还有其他任务),核心线程暂停间隔
|
* @param sleepSmallBusy 小忙时(只有恒久任务,无其他任务),核心线程暂停间隔
|
*/
|
public void setSleep(Long sleepBigBusy, Long sleepSmallBusy){
|
CoreThread.sleepBigBusy = sleepBigBusy ;
|
CoreThread.sleepSmallBusy = sleepSmallBusy ;
|
}
|
|
/**
|
* 核心单线程,执行所有的单线程任务
|
*/
|
@SuppressWarnings("finally")
|
@Override
|
public void run() {
|
Queue coreQueue = CoreUnit.taskQueue ;
|
int count = 0 ;
|
int n = 0 ;
|
while(true){
|
try{
|
/**
|
* 此处取出当前队列的节点数量,作为一个定量count处理,
|
* 原因:
|
* 在处理定量count过程中,可能有的节点又回到队列中,可能新生节点进入队列中,即在处理过程中,队列可能又增长了
|
*/
|
count = coreQueue.size() ;
|
if(count > 0){
|
n = 0 ;
|
while(n < count){
|
CoreTask task = (CoreTask)coreQueue.pop() ;
|
if(task != null){
|
task.excute();
|
}
|
n ++ ;
|
}
|
//大暂停一下
|
sleep(sleepBigBusy) ;
|
}else{
|
//小暂停一下
|
sleep(sleepSmallBusy) ;
|
}
|
}catch(Exception e){
|
log.error("核心线程发生异常" + (e.getMessage() == null ? "" : (":" + e.getMessage())), e);;
|
}finally{
|
continue ;
|
}
|
}
|
}
|
}
|