2017-10-15 106 views
0

我現在正在學習Java中的類和繼承。我做了一個簡單的RPG遊戲。 現在我嘗試使用多線程,但它不起作用。 我希望輸出每30秒出來一次。 「遊戲開始已經過去了30秒。」像這樣.. 這些數字會隨着時間的推移而增長。 我該怎麼辦? 其實,我不會說英語,它可能會很尷尬.. 我會等你的答案。謝謝!如何使用定時器多線程

//import java.util.Timer; 
import java.util.TimerTask; 

public class Timer extends Thread { 

    int count = 0; 

    Timer m_timer = new Timer(); 
    TimerTask m_task = new TimerTask() { 

     public void run() { 
      count++; 
      System.out.println("It's been 30 seconds since the game started."); 
     } 

    }; 

    m_timer.schedule(m_task, 1000, 1000); 
}; 

主營:

public class Main { 

    public static void main(String[] args) { 
     Timer m_timer = new Timer(); 
     m_timer.start(); 
    } 

} 
+1

我想如果你第一次只是在學習課程和繼承,我認爲RPG遊戲對初學者來說太複雜了。爲什麼你需要多線程?它是學校作業的一部分嗎? – markspace

+0

你應該**從不** **'Timer#schedule'準確,**不是**。使用一個硬性的比較來代替,'long start = System.currentTimeMillis();','long current = System.currentTimeMillis;'和'long duration = current - start;'。不要在這種不受控制的環境中使用並行線程。您應該首先組織一個具有中心**邏輯**(通常稱爲「tick」)和**渲染**方法的井結構。在那裏你可以計算遊戲時間並觸發其他計算。 – Zabuza

+0

是......學校作業。 我沒有讓比賽變得困難。簡單的遊戲。 我在這裏添加了多線程,它非常困難.... :( –

回答

0

如果你有興趣瞭解併發你可以通過閱讀Java Tutorial開始。我意識到你說英語不是你的母語,但也許你可以按照這些教程中提供的代碼。

好像你只是想實現一個簡單的例子,所以我會提供以下代碼:

import java.util.Timer; 
import java.util.TimerTask; 

public class TimerMain { 

    public static void main(String[] args) { 
     Timer timer = new Timer(); 
     TimerTask task = new TimerTask(){ 
      private int count = 0; 

      @Override 
      public void run() { 
       count++; 
       System.out.println("Program has been running for " + count + " seconds."); 
      } 
     }; 
     timer.schedule(task, 1000, 1000); 

     //Make the main thread wait a while so we see some output. 
     try { 
      Thread.sleep(5500); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
     //Stop the timer. 
     timer.cancel(); 
    } 

} 

正如其他人所指出的,如果你需要一個高精確度的你應該使用一種不同的方法。我發現this question關於時間精度。