2014-11-03 21 views
0
public class Blank extends WindowController 
{ 
    private int mouseClicks; 

    public void onMousePress(Location point) 
    { 
     mouseClicks++; 
    } 
} 

我的目標是,如果mouseClicks每秒增加一次,而只需點擊一次啓動它。我該如何讓Java每秒鐘都添加到私人int mouseClicks?

+0

我想我可能理解你的問題。你是否希望確保'mouseClicks'每秒最多隻能增加一次,或者每秒增加一次? – 2014-11-03 02:11:09

回答

0

研究使用Thread.sleep(1000);暫停執行一秒鐘。

http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html

+0

這不會阻止awt線程中的其他類型的事件被觸發嗎? – 2014-11-03 02:07:30

+0

@AlexT。 OP沒有說他們使用的是什麼UI工具包。它看起來不像AWT,但是,是的,Thread.sleep可能會阻止事件發送,所以它不好。 OP需要使用任何與[javax.swing.Timer](http://docs.oracle.com/javase/8/docs/api/javax/swing/Timer.html)等效的UI工具包。 – Boann 2014-11-03 02:35:16

-1

您可以測試以來的最後一次點擊通過的時間。

long lLastClickTime = Long.MIN_VALUE; 

public void onMousePress(Location point) { 
    final long lCurrentTime = System.currentTimeMillis(); 
    if(lCurrentTime - lClickLastTime >= 1000) { 
     mouseClicks++; 
     lLastClickTime = lCurrentTime; 
    }   
} 
1

這是我可以得到的最佳解決方案。

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(); 
     } 
    } 
} 
+0

如果增量線程之外的代碼想要讀取'mouseClicks',則這不是線程安全的。考慮用['AtomicInteger'](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html)替換'int'是最簡單的方法線程安全。 – Boann 2014-11-03 02:37:30

+0

編輯爲AtomicInteger使用,但不能讓其他人添加更多的AtomicInteger?這不會使它比整數更安全嗎?我現在感到困惑XD – JClassic 2014-11-03 03:16:50

+0

int值本身不會[其他線程可見](http://docs.oracle.com/javase/tutorial/essential/concurrency/memconsist.html)。使它成爲一個'volatile int'就可以解決這個問題,事實上,AtomicInteger並不一定是最簡單的解決方案,但是如果其他代碼也想更新這個值,因爲volatile屬性本身並不是提供原子增量操作,所以不會阻止[線程干擾](http://docs.oracle.com/javase/tutorial/essential/concurrency/interfere.html)。 – Boann 2014-11-03 03:21:47