如何让Java每秒添加一个私有的int mouseClicks?
我的目标是让if mouseClicks每秒增加一次,而只需单击一次即可启动;暂停执行一秒钟如何让Java每秒添加一个私有的int mouseClicks?,java,jgrasp,Java,Jgrasp,我的目标是让if mouseClicks每秒增加一次,而只需单击一次即可启动;暂停执行一秒钟 您可以测试自上次单击以来经过的时间 public class Blank extends WindowController { private int mouseClicks; public void onMousePress(Location point) { mouseClicks++; } } 这是我能得到的最好的解决办法 long lLast
您可以测试自上次单击以来经过的时间
public class Blank extends WindowController
{
private int mouseClicks;
public void onMousePress(Location point)
{
mouseClicks++;
}
}
这是我能得到的最好的解决办法
long lLastClickTime = Long.MIN_VALUE;
public void onMousePress(Location point) {
final long lCurrentTime = System.currentTimeMillis();
if(lCurrentTime - lClickLastTime >= 1000) {
mouseClicks++;
lLastClickTime = lCurrentTime;
}
}
这难道不能防止awt线程中其他类型的事件被触发吗?@AlexT。OP并没有说他们正在使用什么UI工具包。它看起来不像AWT,但是是的,Thread.sleep可能会阻止事件调度,所以它不好。OP需要使用他们UI工具箱中的任何等价物。我想我可能已经理解了你的问题。您希望确保鼠标单击最多每秒只能增加一次,还是让它自动每秒增加一次?如果增量线程之外的代码想要读取鼠标单击,这是不安全的。考虑用一个简单的方法来替换int,以获得与AtomicInteger一起使用的线程安全性,但是其他人不能仅仅为AtomicInteger添加更多的信息吗?这不会使它比ints更安全吗?我现在感到困惑,因为int值本身是不存在的。将其设置为volatile int可以解决这一问题,实际上,因此AtomicInteger不一定是最简单的解决方案,但如果其他代码也希望更新该值,则是如此,因为volatile本身不提供原子增量操作,因此不会阻止。这一点很好。谢谢你的介绍。我想这是原海报喜欢什么和想要什么的问题。
public class Blank extends WindowController
{
private final AtomicInteger mouseClicks = new AtomicInteger();
private boolean hasStarted = false;
public void onMousePress(Location point)
{
if(!hasStarted){
hasStarted = true;
Thread t = new Thread(){
public void run(){
while(true){
mouseClicks.incrementAndGet(); //adds one to integer
Thread.sleep(1000); //surround with try and catch
}
}
};
t.start();
}
}
}