4

我刚开始学习如何使用界面,我试图弄清楚如何每 10 秒打印一个特定的单词(在本例中为“你好”)。我使用TimerTaskandTimer类来安排我的任务每 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);

     }


}
4

3 回答 3

4

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

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();
    }
}
于 2013-03-15T17:54:30.840 回答
0

像这样的东西,

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

     }
于 2013-03-15T17:49:34.797 回答
0

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

    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;

        }
    }
于 2013-03-16T12:20:06.653 回答