【发布时间】: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