关于java定时器
我正在用java的定时器做一些测试 我的程序启动一个计时器,然后等待2秒钟,取消计时器并打印出j变量 然而,即使我取消了计时器,它仍然在运行。谢谢关于java定时器,java,timer,Java,Timer,我正在用java的定时器做一些测试 我的程序启动一个计时器,然后等待2秒钟,取消计时器并打印出j变量 然而,即使我取消了计时器,它仍然在运行。谢谢 public static Timer time; public static int j=0; public static void main(String[] args) { try { testrun(); Thread.sleep(2000);
public static Timer time;
public static int j=0;
public static void main(String[] args)
{
try {
testrun();
Thread.sleep(2000);
time.cancel();
System.out.println("timer stop");
System.out.println(j);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void testrun()
{
time = new Timer();
time.schedule(new TimerTask() {
@Override
public void run() {
for(int i = 0;i<100;i++){
System.out.println(i);
j++;
}
System.out.println("End timer");
}
}, 1000, 1000);
}
公共静态定时器时间;
公共静态int j=0;
公共静态void main(字符串[]args)
{
试一试{
testrun();
《睡眠》(2000年);
时间。取消();
System.out.println(“计时器停止”);
系统输出println(j);
}捕捉(中断异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
公共静态void testrun()
{
时间=新计时器();
时间表(新的TimerTask(){
@凌驾
公开募捐{
对于(int i=0;i,因为cancel
仅中止计时器-如果任务已开始,它将运行到完成
如果您希望中止任务,您需要跟踪它并调用它的interrupt
方法
public static Timer time = new Timer();
public static Thread runningThread = null;
public static int j = 0;
public static void main(String[] args) {
try {
testrun();
Thread.sleep(2000);
time.cancel();
System.out.println("timer stop");
if (runningThread != null) {
// Interrupt the thread.
runningThread.interrupt();
}
System.out.println(j);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void testrun() {
time.schedule(new TimerTask() {
@Override
public void run() {
// Catch the thread that is running my task.
runningThread = Thread.currentThread();
for (int i = 0; i < 100; i++) {
System.out.println(i);
j++;
}
System.out.println("End timer");
}
}, 1000, 1000);
}
公共静态计时器时间=新计时器();
公共静态线程runningThread=null;
公共静态int j=0;
公共静态void main(字符串[]args){
试一试{
testrun();
《睡眠》(2000年);
时间。取消();
System.out.println(“计时器停止”);
if(runningThread!=null){
//中断线程。
runningThread.interrupt();
}
系统输出println(j);
}捕捉(中断异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
公共静态void testrun(){
时间表(新的TimerTask(){
@凌驾
公开募捐{
//捕获正在运行我的任务的线程。
runningThread=Thread.currentThread();
对于(int i=0;i<100;i++){
系统输出打印LN(i);
j++;
}
System.out.println(“结束计时器”);
}
}, 1000, 1000);
}
调用Timer.cancel()
将停止执行任何进一步计划但未执行的任务,但不会中断正在运行的任务
见(我的重点):
终止此计时器,丢弃所有当前计划的任务。不会干扰当前正在执行的任务(如果存在)
可能重复的