2015-04-03 66 views
-1

我有以下代碼:變化而變化

private boolean votesEnabled = false; 

其設置爲我的課開始。 在某行動的號召,我想從false值更改爲true

if (chatMessage.getText().equals("!newGame")) { 
// change the value of votesEnabled for 90 seconds 
} 

現在,在另外兩起案件,我有這樣的事情:

if (chatMessage.getText().equals("!lose") && votesEnabled == true) { 

    // check, if the person already placed a bet: 
    if (!currentPlayers.contains(chatMessage.getName())) { 

     // Add the name to the list of betters 
     currentPlayers.add(chatMessage.getName()); 

     // write it in to the text-file 
     try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(loserlist, true)))) { 
      writer.println(chatMessage.getName()); 
     } 
    } 
} 

...你這個想法。

現在我的問題:我必須擴展線程類來實現嗎?當90秒(在!startGame之後)通過時,不會觸發投票。沒有線程可行嗎?此外,變量必須在90秒後再次設置爲false。

簡單的例子

// Start => votesEnabled = false 
// !newGame => votesEnabled = true 
// 91 secs after !newGame => votesEnabled = false 

謝謝您的幫助

+0

不是。可能是控制檯應用程序。沒有窗戶(或類似的東西) – DasSaffe 2015-04-03 12:13:18

+0

想到一個計時器。不,你不應該爲任何事情擴展線程。如果你需要線程,你幾乎總是會實現Runnable,因爲任何體面的線程教程都會告訴你。 – 2015-04-03 12:15:33

+0

我想如果你把邏輯放到方法而不是變量中,你可以在沒有額外線程的情況下進行:當你將它改爲true時,保存當前時間。然後,當您調用該方法時,它將檢查當前時間是否比前一個時間短90秒。 – RealSkeptic 2015-04-03 12:29:20

回答

0

要在我的評論擴大:

定義變量votesEnabled的相反,定義:

private long lastVoteTimeMillis = 0L; 
private static final long VOTE_PERIOD = 90000L; 

然後定義兩種方法:

使用

if (chatMessage.getText().equals("!newGame")) { 
    enableVotes(); 
} 

,然後進行測試:

private void enableVotes() { 
    lastVoteTimeMillis = System.currentTimeMillis(); 
} 

private boolean votesEnabled() { 
    return System.currentTimeMillis() - lastVoteTimeMillis < VOTE_PERIOD; 
} 

現在你可以做

if (chatMessage.getText().equals("!lose") && votesEnabled()) { 
    // Do your vote-dependent stuff 
} 

這可以確保在90秒以內,因爲通過您的投票依賴的東西纔會被執行!newGame

您可以爲其添加靈活性。例如,您可以確保在設置lastVoteTimeMillisenableVotes()之前,先不檢查投票時間,以確保投票時間不能超過90秒。您可以添加一個disableVotes()方法,該方法將lastVoteTimeMillis設置爲0L,因此在下一個查詢中它將超過90秒。

該解決方案根本不需要額外的線程,既不是由Timer創建的線程也不是ThreadRunnable的擴展。但是如果你的遊戲已經是多線程的,那麼一定要使lastVoteTimeMillis變量爲volatile

-1
if (chatMessage.getText().equals("!newGame")) { 
// change the value of votesEnabled for 90 seconds 
votesEnabled = true; 
sleep(90000); 
votesEnabled = false; 
}