本文介绍了如何TimerTask的Andr​​oid上管理线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道怎么一个TimerTask正在与线程。

I was wondering how the TimerTask is working with threads.

例如,我有一个执行TimerTask的,它有它运行在UI线程一个'运行'方法的code。

For example, I've got a code that executes a TimerTask, which has a 'run' method which will run on the UI Thread.

class looper extends TimerTask {

    public looper() {

    }

    public void run() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                timer.schedule(new looper(), new Date(new Date().getTime() + 100));
            }
        });
    }
}

和计时器就开始这样的:

and the timer would start like this:

    timer = new Timer();
    timer.schedule(new looper(), new Date());

请问TimerTask的创建一个新的线程?如果是这样,如何​​ runOnUiThread 将工作?将它移到了code到UI线程?

Will the TimerTask create a new thread? if so, how does runOnUiThread will work? will it move the code to the UI thread?

我试过,无需再次调用TimerTask的( timer.schedule ),只是使用在运行一个无限循环来进行计算 - 但会阻止用户界面线程和应用程序不响应

I've tried to eliminate the need to call the TimerTask again (timer.schedule) and just use an infinite loop inside the run to make calculations - but that would block the UI thread and the app will not respond.

PS - 我必须在UI线程上的code运行,因为它有更新UI

P.S - I must have the code run on the UI thread, because it has to update the UI.

那么,到底是怎么回事?

So, what's going on here?

推荐答案

关于你的问题:

  • runOnUiThread 从文档:

运行在UI线程上指定的操作。如果当前线程是UI线程,则该动作被立即执行。如果当前线程不是UI线程,该操作被张贴到UI线程的事件队列。

在code在TimerTask的是在不同的线程中执行,所以你应该叫 runOnUiThread 执行code。

  • The code at TimerTask it is executed on a different thread, so you should call runOnUiThread to execute code.

    您这样做是对的,但你为什么要重新创建一个TimerTask的run方法?考虑使用 scheduleAtFixedTime 时,100会期及延迟0。run方法,然后将执行它应该做的工作。

    You are doing it right, but why are you re-creating the timertask at the run method ? Consider using scheduleAtFixedTime , the 100 will be the period and the delay 0.The run method then will execute the task it is supposed to do.

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //do whatever
            }
        });
    

    scheduleAtFixedTime

    *的更新:

    如果其更新到视图,最好是使用 handler.postDelayed ,看到一个<一个href="http://stackoverflow.com/questions/6242268/repeat-a-task-with-a-time-delay?answertab=votes#tab-top">example这里它将在UI线程上的延迟之后执行。

    If its an update to a view it is better to use handler.postDelayed, see an example here it will be executed after a delay on the UI thread.

    这篇关于如何TimerTask的Andr​​oid上管理线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

  • 09-01 16:23