3

当我使用 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();
4

1 回答 1

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

于 2012-07-25T14:40:12.790 回答