1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.dy.common.mw.core;
 
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
 
import java.util.Timer;
import java.util.TimerTask;
 
/**
 * @Author: liurunyu
 * @Date: 2024/11/21 13:41
 * @Description
 */
public class CoreTimer extends TimerTask {
 
    private static final Logger log = LogManager.getLogger(CoreTimer.class.getName()) ;
 
    private static final CoreTimer instance = new CoreTimer() ;
 
    private Long workInterval = 100L ;//核心线程暂停间隔
 
    private Timer timer;
 
    private boolean stop;
 
    private CoreTimer(){
        this.timer = new Timer();
        this.stop = false ;
    }
 
    public static CoreTimer getInstance(){
        return instance ;
    }
 
    public void stop(){
        this.stop = true ;
        if(this.timer != null){
            this.timer.cancel();
        }
    }
    public boolean isStop(){
        return this.stop ;
    }
 
    /**
     * 设置/核心线程暂停间隔
     * @param workInterval /核心线程暂停间隔
     */
    public void setSleep(Long workInterval){
        this.workInterval = workInterval ;
    }
 
    public void start(){
        this.timer.schedule(this, 0 , this.workInterval);
    }
 
    /**
     * TimerTask的run方法
     */
    @Override
    public void run() {
        try{
            /**
             * 此处取出当前队列的节点数量,作为一个定量count处理,
             * 原因:
             * 在处理定量count过程中,可能有的节点又回到队列中,也可能新生节点进入队列中,即在处理过程中,队列可能又增长了
             */
            int count = CoreUnit.taskQueue.size() ;
            while(count > 0){
                CoreTask task = (CoreTask)CoreUnit.taskQueue.pop() ;
                if(task != null){
                    task.execute();
                }
                count-- ;
            }
        }catch(Exception e){
            log.error("核心线程发生异常" + (e.getMessage() == null ? "" : (":" + e.getMessage())), e);;
        }
    }
}