运行循环每一秒的Java [英] Run loop every second java

查看:203
本文介绍了运行循环每一秒的Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int delay = 1000; // delay for 1 sec. 
int period = 10000; // repeat every 10 sec. 
Timer timer = new Timer(); 
timer.scheduleAtFixedRate(new TimerTask() 
    { 
        public void run() 
        { 
            displayData();  // display the data
        } 
    }, delay, period);  

和其他的:

while(needToDisplayData)
{
    displayData(); // display the data
    Thread.sleep(10000); // sleep for 10 seconds
}   

他们都不起作用(应用程序强制关闭)。还有什么其他的选择,我可以试试吗?

Both of them doesn't work (application is force closed). What other options I can try?

推荐答案

您code失败,因为你在后台线程中执行的睡眠,但显示的数据必须在UI线程中执行。

You code is failed because you perform sleep in background thread but display data must be performed in UI thread.

您必须从runOnUiThread(可运行),运行displayData或定义处理程序,并发送信息给它。

You have to run displayData from runOnUiThread(Runnable) or define handler and send message to it.

例如:

(new Thread(new Runnable()
        {

            @Override
            public void run()
            {
                while (!Thread.interrupted())
                    try
                    {
                        Thread.sleep(1000);
                        runOnUiThread(new Runnable() // start actions in UI thread
                        {

                            @Override
                            public void run()
                            {
                                displayData(); // this action have to be in UI thread
                            }
                        });
                    }
                    catch (InterruptedException e)
                    {
                        // ooops
                    }
            }
        })).start(); // the while thread will start in BG thread

这篇关于运行循环每一秒的Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆