【问题标题】:Pause and resume a thread via key press通过按键暂停和恢复线程
【发布时间】:2016-12-05 13:33:03
【问题描述】:

我想通过按键暂停和恢复线程。这个想法是线程生成数字,这些数字通过管道发送到另一个线程,用户可以通过按“p”键暂停和恢复线程。我现在是这样的:线程一直等到我按下任何键并且随机数显示在屏幕上(输出是另一个线程),然后线程一直等到我按下另一个键......但是如果我按下'p ' 线程停止,我无法让它恢复。

import java.io.IOException;
import java.util.Random;
import java.io.PipedOutputStream;
import java.util.Scanner;


public class Producer extends Thread {
    private static final int MIN = 0;
    private static final int MAX = 60;
    private volatile boolean pause;
    private PipedOutputStream output = new PipedOutputStream();

public Producer(PipedOutputStream output) {
    this.output = output;
}

@Override
public void run() {
    Random rand = new Random();

    Scanner reader = new Scanner(System.in);
    int random;
    String key = "p";
    String keyPressed;
    try {     
        while (true) {
            keyPressed = reader.next();
            if (keyPressed.equalsIgnoreCase(key)) {
                pauseThread();
            } else {
                random = rand.nextInt(MAX - MIN + 1);
                output.write((int) random);
                output.flush();
                Thread.sleep(1000);

            }
            if (pause = true && keyPressed.equalsIgnoreCase(key)) {
                    resumeThread();
            }
        }
        output.close();
    } catch (InterruptedException ex) {
        interrupt();
    } catch (IOException ex) {
        System.out.println("Could not write to pipe.");
    }
}

public synchronized void pauseThread() throws InterruptedException {
    pause = true;
    while (pause)
        wait();
}

public synchronized void resumeThread() throws InterruptedException {
    while (pause) {
        pause = false;
    }
    notify();
}

}

【问题讨论】:

  • 好的。问题是什么?
  • 你不应该这样做。将BlockingQueue 传递给您的线程并使其通过它推送所有数字。然后,您可以停止从队列中读取以暂停您的进程。
  • 或者 - 你可以试试stackoverflow.com/a/10669623/823393
  • 1) 我认为您至少需要两个线程,一个“worker”,另一个暂停/取消暂停 worker 2) 您应该知道 volatilesynchronized 之前。 3) pause = true 不是你想的那样——要么避免这种比较(只需使用pause),要么采用将常量写入左侧的C 约定(true = pause 将给出编译错误)。 4) 除非出于教育目的,否则您应该使用 Executors Framework

标签: java multithreading


【解决方案1】:

也许暂停的线程不是应该读取键盘的线程。

【讨论】:

    【解决方案2】:

    只需在run 中评论pauseThread() 方法 当然,您应该评论resumeThread,因为不需要这些方法。我的意思是,当您按下“p”时,您只需要跳过主要方法即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-24
      • 1970-01-01
      • 2010-12-28
      • 1970-01-01
      • 1970-01-01
      • 2015-02-21
      相关资源
      最近更新 更多