簡體   English   中英

如何暫停執行線程?

[英]How to pause the execution of Thread?

在下面的示例程序中,我需要ThreadCountcount.sleep()調用30000 ms時暫停向控制台寫入,並且應在每個1000 ms時間間隔內發生。 當我運行程序時,不會停止向控制台進行寫入。 它連續打印而無需等待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());
                }
            }
        }
    }
}

RunMeTask線程將不等待Count。 兩個線程是分開的,並且分別執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM