Thread 结合 Timer一起使用

首先,大家在开发的时候,有时候做一些耗时任务时,难免会用到线程【Thread】,以免阻塞主线程。但是,有时候,我们只希望这个在线程里面执行的任务,不能太长,意思就是说,我需要在这个线程执行一段时间后,无论有没有完成我制定的任务,都要讲线程终止掉。这个时候又要用到【Timer】了。

变量声明:

    private static final int TIME_LIMIT = 15000; // 登陆超时时间 15秒
    Timer timer;
    Thread thread;

 final Handler myHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case TIME_OUT:
                    // 打断线程
                    thread.interrupt();
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                     // deal with what you should do after thread job is failed
                    break;
                case SUCCESS:
                    // 取消定时器
                    if (timer != null) {
                        timer.cancel();
                    }
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    // do what you want after thread job is successed
   
                    break;
                default:
                    break;
            }
        }
    };

具体方法:

 timer = new Timer();

 thread = new Thread(new Runnable() {
                @Override
                public void run() {   
                      if(doYourJob())              
                        //after work  is done...
                        Looper.prepare();
                        sendSuccessMsg();
                        Looper.loop();
                    } else {
                        //work is fail
                        errorDialog( "sorry work is not done !");
                    }
                }
            });

            thread.start();
            // 设定定时器
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    sendTimeOutMsg();
                }
            }, TIME_LIMIT);

补充:

    /**
     * 错误对话框
     *
     * @param errorText
     */
    private void errorDialog(String errorText) {
        if (dialog != null) {
            dialog.dismiss();
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this); // 先得到构造器
        builder.setTitle("提示"); // 设置标题
        builder.setMessage(errorText); // 设置内容
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { // 设置确定按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss(); // 关闭dialog
            }
        });
        // 参数都设置完成了,创建并显示出来
        builder.create().show();
    }

    /**
     * // 向handler发送超时信息
     */
    private void sendTimeOutMsg() {
        Message timeOutMsg = new Message();
        timeOutMsg.what = TIME_OUT;
        myHandler.sendMessage(timeOutMsg);
    }
  /**
     * // 向handler成功信息
     */
  private void sendSuccessMsg() {
        Message timeOutMsg = new Message();
        timeOutMsg.what = SUCCESS;
        myHandler.sendMessage(timeOutMsg);
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 从哪说起呢? 单纯讲多线程编程真的不知道从哪下嘴。。 不如我直接引用一个最简单的问题,以这个作为切入点好了 在ma...
    Mr_Baymax阅读 2,912评论 1 17
  • 目录(GCD): 关键词 混淆点 场景应用 总结 1. 关键词 线程概念: 独立执行的代码段,一个线程同时间只能执...
    Ryan___阅读 1,374评论 0 3
  • Object C中创建线程的方法是什么?如果在主线程中执行代码,方法是什么?如果想延时执行代码、方法又是什么? 1...
    AlanGe阅读 1,920评论 0 17
  • 下面是我自己收集整理的Java线程相关的面试题,可以用它来好好准备面试。 参考文档:-《Java核心技术 卷一》-...
    阿呆变Geek阅读 15,142评论 14 507
  • 原文地址 http://www.cnblogs.com/kenshincui/p/3983982.html 大家都...
    怎样m阅读 1,428评论 0 1

友情链接更多精彩内容