gpt4 book ai didi

java - 如何在 java 中创建一个带有名称的 timer.scheduler ..?

转载 作者:行者123 更新时间:2023-11-29 10:13:49 25 4
gpt4 key购买 nike

我正在 run() 中执行多个 Timer.schedulers,我想知道哪个调度程序执行的任务。请引用这段代码:

   Timer timer = new Timer();

for (int i=0;i<10;i++)
{
timer.schedule(task, 5000);
}

这里执行了 10 次任务,但我无法找到哪个计时器执行了哪个任务。所以检查了api没有setName()。有什么方法可以设置调度程序的名称吗?

请帮帮我...

最佳答案

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

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

    public void run() {
Thread.currentThread().setName("Task name");
}

要知道哪个调度器正在运行,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();
}

因此,将其用作:

 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());
//...

}
}

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

关于java - 如何在 java 中创建一个带有名称的 timer.scheduler ..?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24156315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com