Java创建后台线程,该线程定期执行某些操作 [英] Java create background thread which does something periodically

查看:313
本文介绍了Java创建后台线程,该线程定期执行某些操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建一个单独的后台线程来单独做一些事情? 我已经尝试了以下程序,但无法正常运行.

Is it possible to create a separate background thread which would separately do some stuff? I've tried the following program but it doesn't work as I expect.

public class Test {

    private static class UpdaterThread extends Thread {
        private final int TIMEOUT = 3000;

        public void run() {
            while (true) {
                try {
                    Thread.sleep(TIMEOUT);
                    System.out.println("3 seconds passed");
                } catch (InterruptedException ex) {
                }
            }
        }
    }

    /**
     * @param args
     *            the command line arguments
     */
    public static void main(String[] args) {
        try {
            Thread u = new UpdaterThread();
            u.start();
            while (true) {
                System.out.println("--");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

我希望每3秒就会在多个-"字符串流中打印过去3秒". 实际上,从不打印"3秒过去".为什么?以及如何创建一个后台线程,它将独立于主线程执行某项操作?

I expected that every 3 seconds "3 seconds passed" will be printed in the flow of multiple "--" strings. In fact "3 seconds passed" is never printed. Why? And how can I create a background thread which would do something independantly from the main thread?

推荐答案

使用java.util.TimerTaskjava.util.Timer:

Timer t = new Timer();

t.scheduleAtFixedRate(
    new TimerTask()
    {
        public void run()
        {
            System.out.println("3 seconds passed");
        }
    },
    0,      // run first occurrence immediately
    3000);  // run every three seconds

这篇关于Java创建后台线程,该线程定期执行某些操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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