java定期执行一个方法

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用

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

标签: isp

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:Java开发之文件下载

下一篇:使用javamail发送包含图片的html格式邮件