简体   繁体   English

如何暂停执行线程?

[英]How to pause the execution of Thread?

In the below sample program I need that Thread class Count should pause writing to console when count.sleep() call for 30000 ms and it should happen in each time interval of 1000 ms . 在下面的示例程序中,我需要ThreadCountcount.sleep()调用30000 ms时暂停向控制台写入,并且应在每个1000 ms时间间隔内发生。 When I am running the program, the writing to console is not stopping. 当我运行程序时,不会停止向控制台进行写入。 It prints continuously without waiting for 30000 ms . 它连续打印而无需等待30000 ms Please help me to understand what's going wrong. 请帮助我了解发生了什么问题。

What is the solution to stop the Thread class Count for specific time of period in each time interval? 在每个时间间隔的特定时间段内停止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());
                }
            }
        }
    }
}

RunMeTask thread will wait not the Count. RunMeTask线程将不等待Count。 Both threads are separate and execute separately. 两个线程是分开的,并且分别执行。

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

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