如何在一定的时间间隔后重复运行一个线程

编程入门 行业动态 更新时间:2024-10-13 22:19:22
本文介绍了如何在一定的时间间隔后重复运行一个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我要运行一个线程(它一些时间在后台耗时的任务,不更新UI),它只是下载了一些文件,形成了互联网,它是独立于用户界面。

I want to run a thread (Which does some time consuming task in background and does NOT update UI) it just downloads some files form the internet and it is independent from the UI.

我想一段时间间隔后重复运行这个线程。

I want to run this thread repeatedly after some time interval.

我怎样才能做到这一点,我有螺纹类似如下:

How can i do this, I have thread something like below:

boolean mResult =false; void onCreate() { DownloadThread mDownloadThread = new DownloadThread(); mDownloadThread.start(); } class DownloadThread extends Thread implements Runnable { public void run() { // My download code mResult = result; } }

我是否需要使用处理程序实施呢?

推荐答案

选项1:

volatile boolean flag = true; public void run() { while(flag) { // Do your task try{ Thread.Sleep(interval); } catch(Exception e){ } } }

选项2:

Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { // Do your task } }, 0, interval);

选项3:

volatile boolean flag = true; public void someMethod(){ // Do your task try{ Thread.Sleep(interval); } catch(Exception e){ } if(flag) return; else someMethod(); }

方法4:

final Handler handler = new Handler(); volatile boolean flag = true; Class A implements Runnable{ public void run(){ // Do your Task } if(!flag) handler.postDelayed(a, interval); } A a = new A(); handler.postDelayed(a);

将有更多的选择。我从来没有尝试过的选项3和4,刚来到我的脑海里,我写道。如果我是你,我会使用任何1或2。

There will be many more options. I never tried option 3 and 4. It just came to my mind and I wrote. If I were you I would use any of 1 or 2.

更多推荐

如何在一定的时间间隔后重复运行一个线程

本文发布于:2023-11-22 03:49:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615865.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:在一   线程   间隔   时间

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!