Java 计时器获取任务执行线程
有没有办法获取TimerTask将在其上运行的线程Java 计时器获取任务执行线程,java,multithreading,timer,task,scheduled-tasks,Java,Multithreading,Timer,Task,Scheduled Tasks,有没有办法获取TimerTask将在其上运行的线程 public class Main { static Thread gameThread= null; public static void main(String[] args) throws Exception { Timer t = new Timer(); t.schedule(new TimerTask(){ { gameTh
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 Concurrency在实践中推荐),这实际上非常简单:
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);
}
}
相关文档的链接:
- ,
- ,