import java.util.*;
public class TestTimer
{
public static void main(String[] args)
{
new Timer().schedule(new TimerTask() //匿名类
{
public void run()
{
try
{
Runtime.getRuntime().exec("notepad.exe");
}
catch(Exception e)
{
e.printStackTrace();
}
//结束任务线程的代码
//Timer.cancel();
//TimerTask.cancel();
}
},
5000);
}
}
public class TestTimer
{
public static void main(String[] args)
{
new Timer().schedule(new TimerTask() //匿名类
{
public void run()
{
try
{
Runtime.getRuntime().exec("notepad.exe");
}
catch(Exception e)
{
e.printStackTrace();
}
//结束任务线程的代码
//Timer.cancel();
//TimerTask.cancel();
}
},
5000);
}
}
/*
*功能:程序启动5秒后,打开记事本应用程序
*缺陷:因为使用了匿名类,所以程序中注释的代码即使取消注释也不能结束new Timer的线程
*About Thread:When code running in some thread creates a new Thread object,
* the new thread has its priority initially set equal to the priority
* of the creating thread, and is a daemon thread if and only if the creating
* thread is a daemon.
*解决:如果想在启动记事本后终止程序,即使线程停止,则不可使用匿名类。
*如下可以实现:
import java.util.*;
public class TestTimer
{
public static void main(String[] args)
{
Timer tm = new Timer();
tm.schedule(new MyTimerTask(tm),5000);
}
}
*功能:程序启动5秒后,打开记事本应用程序
*缺陷:因为使用了匿名类,所以程序中注释的代码即使取消注释也不能结束new Timer的线程
*About Thread:When code running in some thread creates a new Thread object,
* the new thread has its priority initially set equal to the priority
* of the creating thread, and is a daemon thread if and only if the creating
* thread is a daemon.
*解决:如果想在启动记事本后终止程序,即使线程停止,则不可使用匿名类。
*如下可以实现:
import java.util.*;
public class TestTimer
{
public static void main(String[] args)
{
Timer tm = new Timer();
tm.schedule(new MyTimerTask(tm),5000);
}
}
class MyTimerTask extends TimerTask
{
private Timer tm = null;
public MyTimerTask(Timer tm)
{
this.tm = tm;
}
public void run()
{
try
{
Runtime.getRuntime().exec("notepad.exe");
}
catch(Exception e)
{
e.printStackTrace();
}
tm.cancel();
}
}
*/
{
private Timer tm = null;
public MyTimerTask(Timer tm)
{
this.tm = tm;
}
public void run()
{
try
{
Runtime.getRuntime().exec("notepad.exe");
}
catch(Exception e)
{
e.printStackTrace();
}
tm.cancel();
}
}
*/
本文转自 august 51CTO博客,原文链接:http://blog.51cto.com/august/6957,如需转载请自行联系原作者