为每个TimerTask创建不同的Timer对象,想停止某个Timer直接调用其cancel()方法 ,写个小例子import java.util.Date;import java.util.Timer;import java.util.TimerTask;public class Test{ public static void main(String args[]) throws InterruptedException { TimerTask task1=new TimerTask(){ public void run() { // TODO Auto-generated method stub System.out.println("task1"); } }; TimerTask task2=new TimerTask(){ public void run() { // TODO Auto-generated method stub System.out.println("task2"); } }; Timer t1=new Timer(); Timer t2=new Timer(); t1.schedule(task1, new Date(), 1000);//每隔一秒输出 t2.schedule(task2, new Date(), 1000);//每隔一秒输出 Thread.sleep(5000);//等待5秒 t1.cancel();//停止定时器t1 Thread.sleep(5000);//等待5秒 t2.cancel();//停止定时器t2 }} |