Java:如何中止从System.in读取的线程 [英] Java: how to abort a thread reading from System.in

查看:254
本文介绍了Java:如何中止从System.in读取的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java线程:

I have a Java thread:

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()调用,以便该线程打印中止。?我尝试了 System.in.close(),但这没有任何区别, stdin.readline()仍在阻止。

In another thread, how do I abort the stdin.readline() call in this thread, so that this thread prints Aborted.? I have tried System.in.close(), but that doesn't make any difference, stdin.readline() is still blocking.

我对没有


  • 忙的解决方案感兴趣等待(因为这会烧掉100%的CPU);

  • 睡觉(因为那时程序没有立即响应 System.in ) 。

  • busy waiting (because that burns 100% CPU);
  • sleeping (because then the program doesn't respond instantly to System.in).

推荐答案

我的第一反应是线程 System.in 真的不能一起使用。

My first reaction is that a thread and System.in really don't go together.

首先,拆分这个以便线程代码不接触任何静态包括 System.in

So first, split this so that the thread code does not touch any static including System.in.

一个线程从读入InputStream 并传入缓冲区。将 InputStream 传递到从缓冲区读取的现有线程中,但也检查您是否未中止。

A thread reads from InputStream and passes into a buffer. Pass an InputStream into your existing thread that reads from the buffer but also checks that you haven't aborted.

这篇关于Java:如何中止从System.in读取的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆