有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何暂停正在运行的线程并在需要时重新启动同一线程?

我想通过迭代消息列表暂停正在文件中写入消息的线程。当消息列表为空时,我希望线程停止,当消息在列表中时线程恢复

我知道stop、suspend()和resume方法是不推荐使用的,但若线程持续在后台,它会消耗cpu。我在谷歌上搜索了很多次,但找不到正确的答案。请任何人帮帮我

这是我的密码:

 private Thread mFileWriterThread = new Thread() {

    @Override
    public synchronized void run()         {
        while (mIsRunning) {
            synchronized (mMessageList) {
                Iterator it = mMessageList.iterator();
                while ((it.hasNext())) {
                    String message = (String) it.next();
                    writeToFile(fileOutputStream, message);
                    mMessageList.remove(message);

                }
            }
        }
    }

};

共 (2) 个答案

  1. # 1 楼答案

    您希望使用wait()来生成线程块*。然后调用notify()再次唤醒线程。谷歌的“java等待通知”将为您提供一个教程

    *这里的阻塞意味着在不使用任何资源的情况下等待,直到其他线程将其唤醒

  2. # 2 楼答案

    这就是BlockingQueue存在的目的。它有一个take()方法,强制线程阻塞,直到对象可用为止。您的问题可以通过简单的生产者-消费者设计来解决

    我在这里粘贴一个取自Oracle示例的小片段:

    class Producer implements Runnable {
       private final BlockingQueue queue;
       Producer(BlockingQueue q) { queue = q; }
       public void run() {
         try {
           while (true) { queue.put(produce()); }
         } catch (InterruptedException ex) { ... handle ...}
       }
       Object produce() { ... }
     }
    
     class Consumer implements Runnable {
       private final BlockingQueue queue;
       Consumer(BlockingQueue q) { queue = q; }
       public void run() {
         try {
           while (true) { consume(queue.take()); }
         } catch (InterruptedException ex) { ... handle ...}
       }
       void consume(Object x) { ... }
     }
    

    当然,消费者和生产者必须以某种方式共享队列(如示例所示,只需将其传递给构造函数即可)