一个简单的例子看java线程机制

本文介绍了一个简单的Java程序,该程序使用Timer类在指定时间后执行特定任务,例如打开记事本应用。通过对比两种实现方式,说明了如何避免使用匿名内部类来更好地控制线程的生命周期。
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);
 } 
}
/*
 *功能:程序启动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();
   }
   
  }
 */
 

本文转自 august 51CTO博客,原文链接:http://blog.51cto.com/august/6957,如需转载请自行联系原作者
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值