简体   繁体   English

如何使用计时器多线程

[英]How to use timer multithreading

I am now studying classes and inheritance in Java. 我现在正在研究Java中的类和继承。 I made a simple rpg game. 我做了一个简单的RPG游戏。 and Now I try to use the multithreading, but it does not work. 现在,我尝试使用多线程,但是它不起作用。 I want the output to come out every 30 seconds. 我希望每30秒输出一次。 "It's been 30 seconds since the game started." “距比赛开始已经30秒了。” like this.. The numbers will grow over time. 这样的数字会随着时间增长。 What should I do? 我该怎么办? Actually, I can't speak English well and it can be awkward.. I'll wait for your answer. 实际上,我的英语说得不好,可能会很尴尬。我会等你的回答。 Thank you! 谢谢!

//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);
};

Main: 主要:

public class Main {

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

}

If you're interested in learning about concurrency you could start by reading the Java Tutorial . 如果您对学习并发性感兴趣,可以先阅读Java教程 I realize you said English is not your native language, but maybe you can follow the code presented in those tutorials. 我意识到您说英语不是您的母语,但是也许您可以按照这些教程中提供的代码进行操作。

It seems like you're just trying to implement a simple example so I'll offer the following code: 似乎您只是在尝试实现一个简单的示例,因此我将提供以下代码:

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();
    }

}

As others have pointed out if you need a high degree of accuracy you should probably use a different approach. 正如其他人指出的那样,如果您需要高度的准确性,则应该使用其他方法。 I found this question regarding timing accuracy. 我发现了有关计时精度的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM