2015-12-20 24 views
1
timer.schedule(new PressTask(), 2000, rand); 

我希望上面的rand在每次執行時都是不同的數字。例如,第一次計時器。 時間表被稱爲,比方說蘭特是5345.下一次它被調用時,它應該是一個不同的數字,而不是5345.我該怎麼做?如何在每次運行TimerTask時使timer.schedule()的週期發生變化?

對不起,這只是我爲自己做的一點練習。

public class Keypress 
{ 
    static Timer timer = new Timer(); 
    static JFrame frame = new JFrame(); 
    static JButton btn = new JButton("start"); 
    static JButton btn2 = new JButton("stop"); 
    static JTextField txt = new JTextField(); 
    static Robot robot; 
    static Random couch = new Random(); 
    static int rand = couch.nextInt(10000 - 5000) + 5000; 

    public static void main(String[] args) 
    { 
System.out.println(rand); 

frame.setSize(500,300); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
btn.addActionListener(new startPress()); 
btn2.addActionListener(new stopPress()); 
    frame.setLayout(new GridLayout(3, 1)); 
frame.add(btn); 
frame.add(btn2); 
frame.add(txt); 

try 
{ 
    robot = new Robot(); 
} 
catch (AWTException e) 
{ 
    e.printStackTrace(); 
} 
frame.setVisible(true); 
} 
static class startPress implements ActionListener 
{ 
    public void actionPerformed(ActionEvent e) 
    { 
     timer.schedule(new PressTask(), 2000, rand); 
    } 
} 
public static class PressTask extends TimerTask 
{ 
public void run() 
{ 
    robot.keyPress(KeyEvent.VK_1); 
    robot.keyRelease(KeyEvent.VK_1); 
} 
} 
static class stopPress implements ActionListener 
{ 
    public void actionPerformed(ActionEvent e) 
    { 
     System.exit(0); 
    } 
} 
} 
+0

這可能是你的答案:[http://stackoverflow.com/questions/8386545/java-timer-with-not-fixed-delay](http://stackoverflow.com/questions/8386545/java-timer -with-not-fixed-delay) – downeyt

+0

你的代碼每次運行時都會給rand一個不同的數字 –

+0

@downeyt謝謝,這解決了這個問題。 – Zerukai

回答

1

怎麼樣ScheduledExecutorService而不是Timer

public ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); 
public Random rand = new Random();  

class Repeater implements Runnable{ 
    private Runnable task; 
    private long interval; 
    private long maxInterval; 
    private TimeUnit unit; 
    public Repeater(Runnable task, long maxInterval, TimeUnit unit){ 
     this.task = task; 
     this.interval = (rand.nextLong())%maxInterval //don't let interval be more than maxInterval 
     this.unit = unit; 
     this.maxInterval = maxInterval; 
    } 

    public void run(){ 
     executor.schedule(new Repeater(task,maxInterval,unit) 
      , interval, unit); 
    } 
} 

class startPress implements ActionListener 
{ 
    public void actionPerformed(ActionEvent e) 
    { 
     int maxIntervalMs = 5000; 
     executor.schedule(new Repeater(new PressTask(),initialIntervalMs,TimeUnit.MILLISECONDS) 
      , rand.nextLong()%maxIntervalMs, TimeUnit.MILLISECONDS); 
    } 
} 

注意:實際上,你可以做同樣的事情用一個Timer而非ScheduledExecutorService,但精彩的書的「Java併發編程實踐」建議在Timer爲多種原因,包括使用ScheduledExecutorService例如,如果從任務中拋出異常並使用更靈活的API,則可以更好地進行處理。

相關問題