手动触发Java定时器的run()方法
所以,我设置了计时器:手动触发Java定时器的run()方法,java,Java,所以,我设置了计时器: timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { ... } }, 5, 5); 所以我想触发这个run()来测试一些东西,而不是等到它被触发。有办法吗?只需在之前创建可运行的对象(不使用匿名类),并使用它创建一个新的线程,然后启动它 像这样的 Runnable runnable = new Runnable() {
timer.scheduleAtFixedRate(new TimerTask()
{
@Override
public void run()
{
...
}
}, 5, 5);
所以我想触发这个
run()
来测试一些东西,而不是等到它被触发。有办法吗?只需在之前创建可运行的
对象(不使用匿名类),并使用它创建一个新的线程
,然后启动它
像这样的
Runnable runnable = new Runnable() {
@Override
public void run() {
/*impl*/
}
};
new Thread(runnable).start();
使用:
为什么要使用执行器或线程仅*运行方法是不够的?:)
*什么时候跑步不够?当我们不能或不想阻止当前线程时 为什么是unnice?我以为你想测试一些东西。顺便说一下:
ScheduledExecutorService
比Timer
更受欢迎:
// single thread pool - you can use any other scheduled thread pool
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
/*impl*/
}
}, 5, 5, TimeUnit.MILLISECONDS);
// define task
TimerTask = tt new TimerTask()
{
@Override
public void run()
{
...
}
};
// schedule
timer.scheduleAtFixedRate(tt,int,int);
// run as any other method :)
tt.run();