Java util.Timer获取任务执行线程

时间:2016-03-12 01:46:13

标签: java multithreading timer task scheduled-tasks

有没有办法获得运行TimerTask的线程?

public class Main {

    static Thread gameThread= null;

    public static void main(String[] args) throws Exception {
        Timer t = new Timer();

        t.schedule(new TimerTask(){
            {
                gameThread = Thread.currentThread();
                System.out.println(Thread.currentThread());//this will only give main thread back
            }
            @Override
            public void run() {
                gameThread = Thread.currentThread();//unnecessary to run every time


            }

        }, 0,15);
    }
}

我知道这会有效,因为run方法是在每个例程中声明线程,但这似乎效率低下。有没有办法让我可以获得任务只能连续运行一次的线程?它不能在TimerTask的构造函数或初始化程序中工作,因为它们在主线程上运行。

1 个答案:

答案 0 :(得分:0)

如果您愿意使用ScheduledExecutorService而不是Timer(由Java Concurrency in Practice推荐),这实际上非常简单:

public class Main {

    static Thread gameThread= null;

    public static void main(String[] args) throws Exception {
        ScheduledExecutorService service = Executors.newScheduledThreadPool(1 /*single-threaded executor service*/,
             new ThreadFactory(){
                  public Thread newThread(Runnable r){
                      gameThread = new Thread(r);
                      System.out.println(gameThread);
                      return gameThread;
                  }
        });


        service.scheduleAtFixedRate(new Runnable(){
            @Override
            public void run() {
                /*do stuff*/
            }

        }, 0,15,TimeUnit.MILLISECONDS);
    }
}

相关文档的链接: