每秒运行循环java

栏目: Java · 发布时间: 5年前

内容简介:翻译自:https://stackoverflow.com/questions/11687011/run-loop-every-second-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


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms for Image Processing and Computer Vision

Algorithms for Image Processing and Computer Vision

Parker, J. R. / 2010-12 / 687.00元

A cookbook of algorithms for common image processing applications Thanks to advances in computer hardware and software, algorithms have been developed that support sophisticated image processing with......一起来看看 《Algorithms for Image Processing and Computer Vision》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

MD5 加密
MD5 加密

MD5 加密工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具