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
package com.dy.common.mw.core;
 
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
 
/**
 * @Author liurunyu
 * @Date 2023/12/19 16:41
 * @LastEditTime 2023/12/19 16:41
 * @Description
 */
/**
 * 2024-11-21 该类已经弃用,改由CoreConstantTimer实现。
 * 当采用Thread实现时,在while(true){}中使用Thread.sleep(),可能导致的严重性能问题,不推荐在循环中使用线程休眠。
 * Java线程实现采用内核线程实现,线程的休眠及唤醒(状态切换)需借助操作系统进行,这是一个极其耗时耗力的操作。
 * 在线程休眠或运行时间较长的情景下,其对性能的影响还不算明显,因为对线程状态的切换并不频繁。
 * 但若线程休眠及运行的时间都很短(例如毫秒/秒),
 * 系统将频繁的对线程状态进行切换,导致严重的性能损耗,并对着循环次数的递增而放大。
 */
@Deprecated
public class CoreConstantThread extends Thread {
 
    private final static Logger log = LogManager.getLogger(CoreConstantThread.class.getName()) ;
 
    private long sleepBigBusy ;
    private long sleepSmallBusy ;
    private CoreTask task ;
 
    public CoreConstantThread(long sleepBigBusy, long sleepSmallBusy, CoreTask task){
        this.sleepBigBusy = sleepBigBusy ;
        this.sleepSmallBusy = sleepSmallBusy ;
        this.task = task ;
    }
 
    @Override
    public void run() {
        if(task != null){
            int count ;
            while (true) {
                try {
                    count = task.execute();
                    if (count == 0) {
                        //小暂停一下
                        Thread.sleep(sleepBigBusy);
                    }else{
                        Thread.sleep(sleepSmallBusy);
                    }
                } catch (Exception e) {
                    log.error("恒久任务" + task.getClass().getName() + "执行时发生异常" + (e.getMessage() == null ? "" : (":" + e.getMessage())), e);
                }
            }
        }
    }
}