繁体   English   中英

每隔X秒打印一个单词

[英]Printing a word every X seconds

我刚刚开始学习如何使用接口,我试图弄清楚如何每10秒打印一个特定的单词(在本例中为“Howdy”)。 我使用TimerTaskTimer类来安排我的任务每10秒运行一次,但我是以正确的方式做的吗?

import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;
import java.util.*;


public class Howdy2 {

    class PrintHowdy extends TimerTask {
        public void run() {
           System.out.println("Howdy!"); 
        }
     }

     public static void main(String[] args){
     Timer timer = new Timer();
     timer.schedule(new PrintHowdy(), 10000);

     }


}

这样的事情应该可以解决问题,并且不需要使用TimerTimerTask

public class Test
{
    public static void main(String... args)
    {
        Thread thread = new Thread()
        {

            public void run()
            {
                while (true){
                    System.out.println("Hello World");
                    try
                    {
                        Thread.sleep(1000); // 1 second
                    } catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        };
        thread.start();
    }
}

像这样的东西,

 public static void main(String[] args){
   while(true) {
new PrintHowdy().run();
Thread.sleep(10000)
}

     }

在这些解决方案中,您还应该考虑在特定条件下停止流动的情况;

    public class TestExecution02 implements Runnable {

        public boolean doLoop = true;

        public void run() {
                //------
            while(doLoop) {
                try {
                    Thread.sleep(10000); // 10 second
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } 
                // do your job until it is closed
            }

            System.out.println("Thread closed !");
        }


        public static void main(String[] args) {

            TestExecution02 testExecution = new TestExecution02();
            Thread myThread = new Thread (testExecution);
            myThread.start();

            // do something.....
            testExecution.doLoop = false;

        }
    }

暂无
暂无

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

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