JAVA:调度Thread工作的最佳方法是什么?

时间:2013-01-24 20:41:15

标签: java multithreading

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

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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();

答案 2 :(得分:0)

要创建一个在程序运行时启动它的线程并在程序关闭时死掉,请将此线程标记为守护线程:

Thread myThread=new Thread();
myThread.setDaemon(true);
myThread.start(); // forget about it, no need to explicitly kill it