1 要建立一个线程,第隔一秒打印一“hello  world”?

解决方案 »

  1.   

    class PrintThread1 extends Thread {    @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
                System.out.println("Hello world");
            }
        }}class PrintThread2 implements Runnable {    public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
                System.out.println("Hello world");
            }
        }}public class TestX {    public static void main(String[] args) {
            // new PrintThread1().start();
            new Thread(new PrintThread2()).start();
        }
      

  2.   

    用匿名类啊。
    public static void main(String[] args) {
    new Thread(){
    public void run(){
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    }
    System.out.println("hello world");
    }
    }.start();
                }
      

  3.   

    public static void main(String[]args) throws Exception {
    new Thread(){
    public void run() {
    while(true) {
    try{
    this.sleep(1000);
    System.out.println("hello world");
    }catch(Exception e) {
    e.printStackTrace();
    }
    }
    }
    }.start();
    }
    不如试下这个
      

  4.   

    import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.TimeUnit;public class Test2 {    public static void main(String[] args) {
            ScheduledExecutorService schedule = Executors.newScheduledThreadPool(1);
            schedule.scheduleAtFixedRate(
                    new PrintHelloWorld(),                      // 任务内容
                    1000 - System.currentTimeMillis() % 1000,   // 延迟多长时间开始启动
                    1000,                                       // 每隔多长时间执行一次
                    TimeUnit.MILLISECONDS                       // 时间单位
                );
        }    private static class PrintHelloWorld implements Runnable {        @Override
            public void run() {
                System.out.printf("%tT,%<tL  %s%n", System.currentTimeMillis(), "hello world");
            }
        }
    }