0

我需要制作一个Thread在程序运行时启动它的工作,并在程序关闭时停止工作。这Thread将每 1 分钟检查一次。

这种调度的最佳方式是什么,使用Thread.sleep()或使用 aTimer或什么?

4

3 回答 3

3

你没有提供任何代码,但是有很多关于这类事情的例子,这里有一个:

import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
       Executors.newScheduledThreadPool(1);

    public void beepForAnHour() {
        final Runnable beeper = new Runnable() {
                public void run() { System.out.println("beep"); }
            };
        final ScheduledFuture<?> beeperHandle =
            scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
        scheduler.schedule(new Runnable() {
                public void run() { beeperHandle.cancel(true); }
            }, 60 * 60, SECONDS);
    }
 }

http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ScheduledExecutorService.html#scheduleAtFixedRate(java.lang.Runnable

于 2013-01-24T20:50:23.293 回答
2

所以你会有类似的东西

public class Application {
     private final ScheduledExecutorService executor;
     private final Runnable task;

     public Application(ScheduledExecutorService executor, Runnable task) {
         this.executor = executor;
         this.task = task;
     }

     public void init() {
         executor.scheduleAtFixedRate(task, 0, 60, TimeUnit.SECONDS);
     }
     public void shutdown() {
         executor.shutdownNow();
     }
}

你将使用类似的东西创建你的应用程序

 // ....
 Application app = new Application(Executors.newSingleThreadScheduledExecutor(), task);
 app.init();
 // ....
 // at end
 app.shutdown();
于 2013-01-24T20:51:50.020 回答
0

要使线程在程序运行时开始工作并在程序关闭时终止,请将此线程标记为守护线程:

Thread myThread=new Thread();
myThread.setDaemon(true);
myThread.start(); // forget about it, no need to explicitly kill it
于 2013-09-15T11:39:05.027 回答