【问题标题】:Java util.Timer get Task Execution ThreadJava util.Timer 获取任务执行线程
【发布时间】:2016-06-27 10:31:29
【问题描述】:

有没有办法获取 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 的构造函数或初始化程序中不起作用,因为它们在主线程上运行。

【问题讨论】:

    标签: java multithreading timer task scheduled-tasks


    【解决方案1】:

    如果您愿意使用 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);
        }
    }
    

    相关文档的链接:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2019-10-08
      • 1970-01-01
      • 1970-01-01
      • 2017-02-16
      • 2013-04-08
      相关资源
      最近更新 更多