我们在开发项目的时候,肯定会遇到一个情况。需要监控某个状态是否改变,又两种,一种是通过定时任务,一种通过守护线程。如果是定时任务,这会消耗大量的资源。当数据量比较多的时候,每次执行都会消耗资源。所以这种情况最好用守护线程。

     守护线程就是启动的时候就启动了。项目结束则结束。

详细代码如下:

@Component
public class StartThread implements DisposableBean,Runnable {

    private Thread thread;


    private volatile boolean someCondition = true;

        

    /*
     *需要执行详细功能的代码
    */
    @Autowired
    private Timer timer;

    // dao 和service注入
    @Autowired
    public StartThread(Timer timer) {
        this.timer = timer;
        this.thread = new Thread(this);
        this.thread.start();
        System.out.print("线程启动");
    }

    @Override
    public void run() {
        while (someCondition) {
            // 数据库调用
            try {
                timer.queryOrderSuccess();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }




    @Override
    public void destroy() throws Exception {
        someCondition = false;
    }
}