每秒运行循环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
}

它们都不起作用(应用进程强制关闭).我还可以尝试其他什么选择?

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

您必须从runOnUiThread(Runnable)运行displayData或定义处理进程并向其发送消息.

例如:

(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

翻译自:https://stackoverflow.com/questions/11687011/run-loop-every-second-java