2017-11-18 57 views
-1

我一直在練習線程,所以我寫了這個定時遊戲,用戶需要猜測正確的數字(範圍從1-10)。如果用戶在時間限制內猜到了正確答案,則線程停止並且程序終止。當用戶在時間限制內未能猜出時,它無法工作。即使它在時間限制之後進入if語句,它仍然不能完全中斷該線程,除非我猜想正確的數字。我已閱讀其他線程,但他們似乎使用詢問有關「傳統」猜謎遊戲或利用Timer。對於建議的解決方案的解釋和/或提示也被讚賞。猜測數字在時間限制內

import java.util.*; 
    import static java.lang.System.out; 
    import java.io.*; 

    public class Threading implements Runnable { 
     private static int num; 
     private static int k; 

    public void run() { 
     try { 
      Scanner line = new Scanner(System.in); 
      k = -1; 
      out.println("Guess!"); 
      while (k != num) { 
       k = line.nextInt(); 
       if (k != num) { 
        out.println("Nope"); 
       } 
      } 

     } 
     catch (Exception e) { 
      out.println("I'm not done!"); 
     } 
    } 

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

     num = (int) (Math.random() * 9 + 1); 
     out.println(num); 
     Thread t = new Thread(new Threading()); 
     t.start(); 

     long patience = 1000 * 5; 
     long startTime = System.currentTimeMillis(); 
     while (t.isAlive()) { 
      t.join(1000); 
      if (((System.currentTimeMillis() - startTime) > patience) && t.isAlive()) { 
       out.println("I'm in here!"); 
       t.interrupt(); 
       t.join(); 
       out.println("Times up!"); 
      } 
     } 
    } 
} 
+1

[如何中斷java.util.Scanner nextLine調用](https://stackoverflow.com/questions/4983065/how-to-interrupt-java-util-scanner-nextline-call) –

+0

@MarkMucha是否有必要使用Streams/Buffers來使代碼正常工作?有沒有辦法結束'nextInt()'的「block」? – TypeHereToSearch

回答

0

由於一個評論已經指出,在調用nextInt會阻止我不認爲有必要進入箇中詳情。

所以現在我會假設你很好,允許用戶1在計時器到期後進行最後的猜測。

以下是修改的代碼,包括我的評論。我把你稱爲t的線程稱爲「猜測線程」。現在

private static int num; 
private static int k; 
//Changed variable "line" to "scanner" and made it static so that the 
// main method can close it once everything is done. 
private static Scanner scanner = new Scanner(System.in); 

public void run() { 
    try { 
     k = -1; 
     System.out.println("Guess!"); 
     while (k!=num) { 
      //Added a check for interrupt, otherwise this thread will never 
      // end unless the user enters the correct answer. 
      if(Thread.currentThread().isInterrupted()) 
       return; 
      k = scanner.nextInt(); 
      if(k != num){ 
       System.out.println("Nope"); 
      } 
     } 
     System.out.println("Correct!"); 

    } catch (Exception e) { 
     System.out.println("I'm not done!"); 
    } 
} 

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

    num = (int) (Math.random() * 9 + 1); 
    System.out.println(num); 
    //Declared the guessing thread as final so it can be used inside of 
    // the TimerTask that is created later. 
    final Thread t = new Thread(new GuessUntilTimeLimit()); 
    t.start(); 

    long patience = 1000 * 5; 

    //Use a Timer to enforce your time limit, the TimerTask will execute 
    // an interrupt of your guessing thread if the thread is still alive 
    // (it may have died already if user got right answer) 
    Timer timer = new Timer(); 
    TimerTask task = new TimerTask(){ 

     @Override 
     public void run() { 
      if(t.isAlive()){ 
       t.interrupt(); 
       System.out.println("Times up! Enter your final guess now."); 
      }    
     } 
    }; 
    timer.schedule(task, patience); 
    //Wait for the guessing thread to finish before canceling the timer 
    t.join(); 
    //By now either the user got the answer or time has run out. Either way 
    // we need to clean up by canceling the timer. 
    timer.cancel(); 
    //Added a call to close the scanner, it's always important to release 
    // resources 
    scanner.close(); 
} 

你的主線程schedules a taskpatience毫秒執行。然後該任務負責interrupting「猜測線程」。 「猜測線程」將檢查interrupt並在適當時自行停止。

同樣,根據您的要求,您可能需要更改接受用戶輸入的方式,因爲nextInt會阻止該線程。爲了完整起見,我在鏈接中提到了評論中提到的question regarding interrupting Scanner.nextLine