java定期执行一个方法

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

在下面的例子中,我们使用DelayedMethod扩展了线程类。这个简称类通过构造函数来指定时间间隔,间隔执行。

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;

public class AnnoyingPopUps extends Applet implements
    ActionListener {
  Button b1, b2;
  DelayedMethod dm;
  int x = 0;

  public void init() {
     b1 = new Button("Start Annoying Popops");
     b2 = new Button("Stop Annoying Popops");
     add(b1); add(b2);
     b1.addActionListener(this);b2.addActionListener(this);
     dm = new DelayedMethod(this, 1000);  // 1 second
     dm.start();
     }

  public void actionPerformed(ActionEvent ae) {
     if (ae.getSource() == b1) {
        dm.oktorun = true;
        }
     else if(ae.getSource() == b2) {
        dm.oktorun = false;
       }s
     }

  public void displayPopup() {
    SimplePopUp d = new SimplePopUp();
    d.show();
    d.setLocation(x , x);
    x = x + 5;
    }

  class SimplePopUp extends Dialog  {
    SimplePopUp() {
      super(new Frame(), "annoying popup");
      this.addWindowListener
       (new WindowAdapter() {
           public void windowClosing(WindowEvent e) {
              e.getWindow().dispose();
              }
           }
       );
     }
   }

  class DelayedMethod extends Thread {
    AnnoyingPopUps myObj = null;  // customize for your need
    boolean oktorun = false;
    int delay;

    DelayedMethod(AnnoyingPopUps myObj) {
      this.myObj = myObj;
      this.delay = 2000;
      }

    DelayedMethod(AnnoyingPopUps myObj, int delay) {
      this.myObj = myObj;
      this.delay = delay;
      }

    public void run() {
      while (true) {
        try {
          sleep(delay);
          if (oktorun) 
              myObj.displayPopup(); // customize this too!
          } 
        catch (InterruptedException ignored) {}
        }
      }
    }    
}