2017-10-15 70 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关于时间精度。