Java创建后台线程,它定期执行某些操作

Ser*_*gey 10 java multithreading

是否有可能创建一个单独的后台线程,它将分别做一些东西?我已经尝试了以下程序,但它没有像我期望的那样工作.

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我期望每3秒"3秒钟过去"将打印在多个" - "字符串流中.事实上,从未打印过"3秒钟".为什么?我怎样才能创建一个后台线程,它可以独立于主线程执行某些操作?

hmj*_*mjd 19

使用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
Run Code Online (Sandbox Code Playgroud)


ass*_*ias 7

它确实打印"3秒钟过去了".删除System.out.println("--"),你会更容易看到它们;-)

现在你也可以使用a ScheduledExecutorService,而Runnable不是使用a Thread:

public class Test {

    private static class Updater implements Runnable {

        @Override
        public void run() {
            System.out.println("3 seconds passed");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Runnable r = new Updater();
        ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
        service.scheduleAtFixedRate(r, 0, 3, TimeUnit.SECONDS);

        Thread.sleep(10000);
        service.shutdown();

    }
}
Run Code Online (Sandbox Code Playgroud)