Java:如何中止从 System.in 读取的线程

2024-01-17

我有一个Java线程:

class MyThread extends Thread {
  @Override
  public void run() {
    BufferedReader stdin =
        new BufferedReader(new InputStreamReader(System.in));
    String msg;
    try {
      while ((msg = stdin.readLine()) != null) {
        System.out.println("Got: " + msg);
      }
      System.out.println("Aborted.");
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
}

}

在另一个线程中,我如何中止stdin.readline()在这个线程中调用,以便这个线程打印Aborted.?我努力了System.in.close(),但这没有什么区别,stdin.readline()仍然阻塞。

我对没有的解决方案感兴趣

  • 忙等待(因为这会消耗 100% CPU);
  • 睡觉(因为这样程序不会立即响应System.in).

海因茨·卡布茨的时事通讯 http://www.javaspecialists.eu/archive/Issue153.html显示如何中止System.in reads:

import java.io.*;
import java.util.concurrent.*;

class ConsoleInputReadTask implements Callable<String> {
  public String call() throws IOException {
    BufferedReader br = new BufferedReader(
        new InputStreamReader(System.in));
    System.out.println("ConsoleInputReadTask run() called.");
    String input;
    do {
      System.out.println("Please type something: ");
      try {
        // wait until we have data to complete a readLine()
        while (!br.ready()) {
          Thread.sleep(200);
        }
        input = br.readLine();
      } catch (InterruptedException e) {
        System.out.println("ConsoleInputReadTask() cancelled");
        return null;
      }
    } while ("".equals(input));
    System.out.println("Thank You for providing input!");
    return input;
  }
}

public class ConsoleInput {
  private final int tries;
  private final int timeout;
  private final TimeUnit unit;

  public ConsoleInput(int tries, int timeout, TimeUnit unit) {
    this.tries = tries;
    this.timeout = timeout;
    this.unit = unit;
  }

  public String readLine() throws InterruptedException {
    ExecutorService ex = Executors.newSingleThreadExecutor();
    String input = null;
    try {
      // start working
      for (int i = 0; i < tries; i++) {
        System.out.println(String.valueOf(i + 1) + ". loop");
        Future<String> result = ex.submit(
            new ConsoleInputReadTask());
        try {
          input = result.get(timeout, unit);
          break;
        } catch (ExecutionException e) {
          e.getCause().printStackTrace();
        } catch (TimeoutException e) {
          System.out.println("Cancelling reading task");
          result.cancel(true);
          System.out.println("\nThread cancelled. input is null");
        }
      }
    } finally {
      ex.shutdownNow();
    }
    return input;
  }
}

现在,我不知道这种方法是否存在泄漏、不可移植或有任何不明显的副作用。就我个人而言,我不愿意使用它。

你也许可以做一些事情蔚来频道 http://download.oracle.com/javase/6/docs/api/java/nio/channels/package-summary.html and 文件描述符 http://download.oracle.com/javase/6/docs/api/java/io/FileDescriptor.html#in- 我自己对它们进行的实验没有产生任何结果。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java:如何中止从 System.in 读取的线程 的相关文章

随机推荐