java学习笔记 java.swing.Timer类中的schedule方法的使用

 第一个参数,是 TimerTask 类,在包:import java.util.TimerTask .使用者要继承该类,并实现 public void run() 方法,因为 TimerTask 类 实现了 Runnable 接口。 第二个参数的意思是,当你调用该方法后,该方法必然会调用 TimerTask 类 TimerTask 类 中的 run() 方法,这个参数就是这两者之间的差值,转换成汉语的意思就是说,用户调用 schedule() 方法后,要等待这么长的时间才可以第一次执行 run() 方法。 第三个参数的意思就是,第一次调用之后,从第二次开始每隔多长的时间调用一次 run() 方法。

Timer和TimerTask一般搭配使用。

贴一段简单的代码

import java.util.*;
public class TimerTest extends TimerTask{
 String index;
 Timer myTimer=new Timer();
 public TimerTest(String index) {
  // TODO Auto-generated constructor stub
  this.index=index;
 }
 @Override
 public void run() {
  // TODO Auto-generated method stub
  System.out.println(index);
 }
 public void start(int delay,int internal) {
  //在delay*1000时间后开始执行TimerTest对象,执行后每隔internal*1000反复执行
  myTimer.schedule(this, delay*1000, internal*1000);
 }
 public void end() {
  myTimer.cancel();   //调用cancle()方法结束
 }
 public static void main(String args[]) {
  //创建和设置myTask对象
  TimerTest myTest=new TimerTest("线程1执行");
  myTest.start(0, 3);

 //创建和设置myTask2对象
  TimerTest myTest2=new TimerTest("线程2执行");
  myTest2.start(0, 1);
  try {
   Thread.sleep(6000);
  } catch (Exception e) {
   // TODO: handle exception
  }
  myTest.end();
  myTest2.end();
 }
}

转载于:https://www.cnblogs.com/GooDBoyS/p/9846529.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值