如何中断对System.in的读取?

时间:2018-03-27 19:04:21

标签: java multithreading inputstream system.in

如果我从System.in开始阅读,它将阻止该线程,直到它获取数据。没有办法阻止它。以下是我尝试过的所有方法:

  • 中断线程
  • 停止线程
  • 结束System.in
  • 调用System.exit(0)确实会阻止该主题,但它也会杀死我的应用程序,所以不理想。
  • 在控制台中输入字符会使方法返回,但我不能依赖用户输入。

不起作用的示例代码:

public static void main(String[] args) throws InterruptedException {
    Thread th = new Thread(() -> {
        try {
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }
    });
    th.start();
    Thread.sleep(1000);
    System.in.close();
    Thread.sleep(1000);
    th.interrupt();
    Thread.sleep(1000);
    th.stop();
    Thread.sleep(1000);
    System.out.println(th.isAlive()); // Outputs true
}

当我运行此代码时,它将输出true并永远运行。

如何以可中断的方式阅读System.in

2 个答案:

答案 0 :(得分:2)

您应该设计run方法,以便它可以自行确定何时终止。在线程上调用stop()或类似方法将是inherently unsafe

但是,仍然存在如何避免在System.in.read中阻塞的问题?为此,您可以轮询System.in.available,直到它返回>在阅读之前0。

示例代码:

    Thread th = new Thread(() -> {
        try {
            while(System.in.available() < 1) {
                Thread.sleep(200);
            }
            System.in.read();
        } catch (InterruptedException e) {
            // sleep interrupted
        } catch (IOException e) {
            e.printStackTrace();
        }
    });

当然,通常认为使用阻塞IO方法而不是轮询是有利的。但民意调查确实有其用途;在你的情况下,它允许这个线程干净地退出。

更好的方法:

避免轮询的better approach将重构代码,以便您打算杀死的任何线程不允许直接访问System.in。这是因为System.in是一个不应该关闭的InputStream。相反,主线程或另一个专用线程将从System.in读取(阻塞),然后将任何内容写入缓冲区。反过来,该缓冲区将由您想要杀死的线程监视。

示例代码:

public static void main(String[] args) throws InterruptedException, IOException {
    PipedOutputStream stagingPipe = new PipedOutputStream();
    PipedInputStream releasingPipe = new PipedInputStream(stagingPipe);
    Thread stagingThread = new Thread(() -> {
        try {
            while(true) {
                stagingPipe.write(System.in.read());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    });     
    stagingThread.setDaemon(true);
    stagingThread.start();
    Thread th = new Thread(() -> {
        try {
            releasingPipe.read();
        } catch (InterruptedIOException e) {
            // read interrupted
        } catch (IOException e) {
            e.printStackTrace();
        }
    });
    th.start();
    Thread.sleep(1000);
    Thread.sleep(1000);
    th.interrupt();
    Thread.sleep(1000);
    Thread.sleep(1000);
    System.out.println(th.isAlive()); // Outputs false
}       

答案 1 :(得分:0)

我编写了一个允许被中断的包装器InputStream类:

package de.piegames.voicepi.stt;
import java.io.IOException;
import java.io.InputStream;

public class InterruptibleInputStream extends InputStream {

    protected final InputStream in;

    public InterruptibleInputStream(InputStream in) {
        this.in = in;
    }

    /**
     * This will read one byte, blocking if needed. If the thread is interrupted while reading, it will stop and throw
     * an {@link IOException}.
     */     
    @Override
    public int read() throws IOException {
        while (!Thread.interrupted())
            if (in.available() > 0)
                return in.read();
            else
                Thread.yield();
        throw new IOException("Thread interrupted while reading");
    }

    /**
     * This will read multiple bytes into a buffer. While reading the first byte it will block and wait in an
     * interruptable way until one is available. For the remaining bytes, it will stop reading when none are available
     * anymore. If the thread is interrupted, it will return -1.
     */
    @Override
    public int read(byte b[], int off, int len) throws IOException {
        if (b == null) {
            throw new NullPointerException();
        } else if (off < 0 || len < 0 || len > b.length - off) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return 0;
        }
        int c = -1;
        while (!Thread.interrupted())
            if (in.available() > 0) {
                c = in.read();
                break;
            } else
                Thread.yield();
        if (c == -1) {
            return -1;
        }
        b[off] = (byte) c;

        int i = 1;
        try {
            for (; i < len; i++) {
                c = -1;
                if (in.available() > 0)
                    c = in.read();
                if (c == -1) {
                    break;
                }
                b[off + i] = (byte) c;
            }
        } catch (IOException ee) {
        }
        return i;
    }

    @Override
    public int available() throws IOException {
        return in.available();
    }

    @Override
    public void close() throws IOException {
        in.close();
    }

    @Override
    public synchronized void mark(int readlimit) {
        in.mark(readlimit);
    }

    @Override
    public synchronized void reset() throws IOException {
        in.reset();
    }

    @Override
    public boolean markSupported() {
        return in.markSupported();
    }
}

调整Thread.yield()只要你可以接受的最大延迟就可以睡觉,并在中断时准备一些例外,但除此之外它应该可以正常工作。