java定期執行一個方法

by57 9年前發布 | 1K 次閱讀 Java

在下面的例子中,我們使用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) {}
    }
  }
}    

}</pre>

 本文由用戶 by57 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!