Util或Swing任何一种Java计时器都让我整个系统挂起,冻结,如何保护系统崩溃?

时间:2012-07-25 11:27:12

标签: java swing time

当我使用util或swing Timer时,系统会挂起/冻结。我怎么能得到这个?

我调用此任务的其他用户界面如下所示,重试后整个系统被冻结。

TimerTask t  = new Task("Local",a); 
java.util.Timer timer = new java.util.Timer();
timer.scheduleAtFixedRate(t, 0, 10000);

尝试3:失败

import java.util.Timer;
import java.util.TimerTask;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

public final class Task extends TimerTask {

  private static Timer timer;
  //private static ui.V v;

  private static int input;
  private static String sinput;

  public static void main (String... arguments ) {
    TimerTask f  = new Task("Local:",20); 
    timer = new Timer();
    timer.scheduleAtFixedRate(f, 0, 10000);   
  }

  public Task(String sinput, int input) {
    this.input = input;
    this.sinput = sinput;
  }

  public void run() {
    System.out.println("Will freeze, dont freeze.....");
    //v = new ui.V(sinput);  loading a user interface
    //v.up(input); show the value
    try {
      Thread.sleep(4000); // wait 4 seconds
    } catch (InterruptedException ex) {
      Logger.getLogger(Task.class.getName()).log(Level.SEVERE, null, ex);
    }
    //v.killme(); // kill the display
    timer.cancel();
  }

}

我也尝试了以下方法,但所有相同的结果系统都被冻结了,手动我必须关闭电源并在PC上。

尝试0:失败

t = new java.util.Timer();
t.schedule(new TimerTask() {
      @Override
   public void run() {
    // same
   }
}, 0, 10000);

尝试1:失败

t = new javax.swing.Timer(10000, new ActionListener() {
  public void actionPerformed(ActionEvent ae) {
    // same
  }
});
t.start();

尝试2:失败

new Thread(new Runnable() {
  public void run() {
   t = new javax.swing.Timer(10000, new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
     // same
    }
   });
t.start();
  }
}).start();

1 个答案:

答案 0 :(得分:1)

奇怪但是因为我开始按照以下方式运行它:(仍然没有显示冻结)

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {

        EventQueue.invokeLater(new Runnable() {

          @Override
          public void run() {
                ....here... timer seems ... less... risky....
            }
        });

    }
});

参考:

https://stackoverflow.com/a/5500371/285594