作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在 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/
我是一名优秀的程序员,十分优秀!