如何在java中创建一个名为timer.scheduler ..?

use*_*081 1 java multithreading timer

我正在执行Timer.schedulers内部数量run(),我想知道哪个调度程序所执行的任务.请参考以下代码:

   Timer timer = new Timer();

   for (int i=0;i<10;i++)
    {
        timer.schedule(task, 5000);
    }
Run Code Online (Sandbox Code Playgroud)

这里执行任务10次,但我无法找到哪个任务由哪个计时器执行.所以检查了api没有setName().有没有办法为调度程序设置名称?

请帮我...

Sha*_*016 8

在您的类扩展中创建一个字段名称,TimerTask并为其提供getter/setter.

或者在运行中执行:(这样您就知道选择了哪个任务)

    public void run() {
            Thread.currentThread().setName("Task name");
     }
Run Code Online (Sandbox Code Playgroud)

要知道哪个调度程序正在运行,Timer中有一个构造函数(请参阅Timer源代码)

     /**
     * The timer thread. (and its the single thread to execute all the scheduled TimerTasks)
     */
  private final TimerThread thread = new TimerThread(queue);

  //Timer constructor
  public Timer(String name) {
            thread.setName(name);
            thread.start();
  }
Run Code Online (Sandbox Code Playgroud)

所以,用它作为:

 Timer timer = new Timer("MyTimerName") 

    class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            //will print timer name 
        System.out.println("Timer Name: "
                        + Thread.currentThread().getName());
            //...

        }
    }
Run Code Online (Sandbox Code Playgroud)

在上述情况下,不要在TimerTask的运行中设置当前线程的名称.