2017-06-15 94 views
1

我在Java中構建一個控制檯遊戲,它的工作原理是這樣的:它爲您打印一個操作(例如:3 x 4),並且您必須編寫結果(本例中爲12),它會在1分鐘內給你操作,然後完成。Java的訪問線程的類屬性

我從一開始,我不得不使用線程來捕捉用戶輸入的知道,所以這是線程的邏輯:

public class UserInput extends Thread { 

    private int answer; 

    @Override 
    public void run() { 
     Scanner in = new Scanner(System.in); 
     while(true){ 
      answer = in.nextInt(); 
     } 
    } 

    public int getAnswer(){ 
     return answer; 
    } 
} 

很簡單,現在遊戲的邏輯:

public static void play() { 

    Game game = new EasyGame();  
    UserInput ui = new UserInput();  
    long beginTime = System.currentTimeMillis()/1000; 

    ui.start();  
    boolean accepted = true; 

    while(timeLeft(beginTime)){ 
     //PrintChallenge() prints an operation and store its result in game 
     if(accepted) game.PrintChallenge(); 
     accepted = false;   
     if(ui.getAnswer() == game.getResult()) accepted = true;  
    } 
} 

//returns if current time is 60 seconds after initial time 
public static boolean timeLeft(long time){  
    return (System.currentTimeMillis()/1000) < (time + 60); 
} 

但它不工作,它根本就不匹配UI的getAnswer()與遊戲的getResult()。我在這個線程和遊戲邏輯上做錯了什麼?

+0

what's game.getResult()在做什麼? – user7294900

+0

當法PrintChallenge()運行時,它打印屏幕(「3×4」爲例)上挑戰並存儲該挑戰到一個變量的結果,那麼game.getResult()返回該變量的值 – DcCoO

+0

嘗試打印'遊戲。的getResult()'。 –

回答

1

我認爲你的問題是Java在本地緩存你的int的值,雖然它可能是由於你的game.getResult()中的某些東西造成的,因爲我無法檢查它。 java中的線程安全很困難。

要確認:

  • 我建的遊戲版本啞巴,沒有任何遊戲邏輯或定時器。
  • 我在你的答案int中添加了一個volatile keyoword,這使得Java檢查主存儲器而不是本地緩存中的int值。

下面的代碼輸出一旦用戶輸入「30」,刪除用戶輸入中的「volatile」keyoword會導致您的情況。

見下文:

package stackOverflowTests; 

import java.util.Scanner; 

public class simpleGame { 
    public static class UserInput extends Thread { 

     volatile private int answer; 

     public void run() { 
      Scanner in = new Scanner(System.in); 
      while(true){ 
       System.out.print("Answer meeee!:"); 
       answer = in.nextInt(); 
      } 
     } 

     public int getAnswer(){ 
      return answer; 
     } 
    } 
    public static void play() throws InterruptedException { 

     UserInput testInput = new UserInput(); 
     testInput.start(); 
     while(true){ 
      //PrintChallenge() prints an operation and store its result on game 
      Thread.sleep(10); 
      if(testInput.getAnswer()==30)System.out.println(testInput.getAnswer()+ " : "+(testInput.getAnswer()==10)); 
     } 
    } 

    public static void main(String[] args) throws InterruptedException{ 
     play(); 

    } 
} 
+0

的'answer'屬性擔任魅力!謝謝 – DcCoO

1
private int answer; 

這個變量必須volatile,因爲你正在閱讀從不同的線程寫它。否則,您需要同步對它的所有訪問,包括讀取和寫入。