如何暂停执行Thread?

时间:2013-12-11 07:28:31

标签: java multithreading

在下面的示例程序中,我需要ThreadCountcount.sleep()调用30000 ms时暂停写入控制台,并且应该在1000 ms的每个时间间隔内发生{1}}。当我运行程序时,写入控制台并没有停止。它可以连续打印而无需等待30000 ms。请帮我理解出了什么问题。

在每个时间间隔内停止ThreadCount特定时段的解决方案是什么?

import java.util.Timer;
import java.util.TimerTask;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author admin
 */
public class Test {

    Test() {
        Count count = new Count();
        count.start();
        TimerTask task = new RunMeTask(count);
        Timer timer = new Timer();
        timer.schedule(task, 1000, 60000);
    }

    public static void main(String[] argu) {
        Test test = new Test();

    }

    public class Count extends Thread {

        @Override
        public void run() {
            int i = 0;
            do {
                System.out.println(i++);
            } while (true);
        }
    }

    public class RunMeTask extends TimerTask {

        private final Count count;

        RunMeTask(Count count) {
            this.count = count;
        }

        @Override
        public void run() {
            synchronized (count) {
                try {
                    count.wait(30000);
                } catch (InterruptedException ex) {
                    System.out.println(ex.toString());
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

RunMeTask线程将不等待Count。两个线程是分开的并且单独执行。