您当前的位置: 首页 > 
  • 2浏览

    0关注

    674博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

两种方式循环检测条件变化handler和sleep

沙漠一只雕得儿得儿 发布时间:2019-03-14 11:47:43 ,浏览量:2

 1.使用handler循环往外抛消息检测
    public void startDetect(long initialDelay, long period){
            Handler handler = new Handler(Looper.getMainLooper());
            runnable = new Runnable() {
                @Override
                public void run() {
                    if(满足条件) {
                        doTask();
                        return;
                    }
                    handler.postDelayed(runnable, 100);
                }
            };
            handler.post(runnable);
        }
2.java中的方法,一个死循环,然后使用sleep隔一段时间检测一下
public class sleepTask {

    static volatile Boolean isInterrupt = false;

    public static void main(String[] args) {

        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                isInterrupt = true;
            }
        };
        Timer timer = new Timer();
        timer.schedule(task, 1000);

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (isInterrupt) {
                        System.out.println("execute task");
                        Thread.currentThread().interrupt();
                        return;
                    } else {
                        try {
                            Thread.sleep(250);
                            System.out.println("waitting ...");
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        };

        Thread thread = new Thread(runnable);
        thread.start();
    }
}

 

关注
打赏
1657159701
查看更多评论
立即登录/注册

微信扫码登录

0.0563s