timer.schedule(new PressTask(), 2000, rand);
我希望上面的兰德每次超过时都是不同的数字。例如,第一次计时器。计划被称为,假设兰德是 5345。下次调用它时,它应该是一个不同的号码,而不是 5345。我该怎么做?
请原谅混乱的编码,这只是我为自己做的一个小练习。
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);
}
}
}
用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 Concurrency in Practice"建议使用ScheduledExecutorService
而不是Timer
,原因有很多,例如,如果从任务中抛出异常,则更好地处理和更灵活的api。