计时线程Runnable和Handler的结合

利用Runnable和Handler,来创建计时线程

private double recodeTime = 0;// 用于计时
private double econdTime = 0;// 用于计时

private boolean flag=true;

private Thread thread;// 计时线程

private Runnable menuTimeTask = new Runnable() {
        public void run() {
            while (flag) {
                try {
                    Thread.sleep(200);
                    recodeTime += 0.2;
                    econdTime += 0.2;
                    handler.sendEmptyMessage(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    return;
                }
            }
        }

        Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case 1:if (recodeTime > 8) {//计时8秒后进行事务逻辑
//                  do what you like
                            recodeTime=0;
                        }if (econdTime > 16) {
                            econdTime=0;
                            recodeTime=0;
                        }
                    break;
                }
            }
        };
    };

/**
* 打开线程
*/
public void startTheard(){
thread=new Thread(menuTimeTask);
thread.start();
}

/**
* 停止线程
*/
public void stopThread(){
flag = false;
}

/**
* 结束线程
*/
public static void destoryThread() {
flag = false;
thread.interrupt();
}

 

 

posted @ 2015-03-02 17:21  草人木  阅读(369)  评论(0编辑  收藏  举报