Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从另一个线程读取System.in_Java_Multithreading_Stdin - Fatal编程技术网

Java 从另一个线程读取System.in

Java 从另一个线程读取System.in,java,multithreading,stdin,Java,Multithreading,Stdin,我目前正在开发一个控制台应用程序,它使用Java7WatchService API观察多个目录。 在main方法中,观察循环发生时,我需要一个单独的线程从系统中读取。在流中,检查观察是否必须停止 我的Runnable实现如下所示: public class InputHandler implements Runnable { @Override public void run() { boolean keepRunning = true; int

我目前正在开发一个控制台应用程序,它使用Java7WatchService API观察多个目录。 在main方法中,观察循环发生时,我需要一个单独的线程从
系统中读取。在
流中,检查观察是否必须停止

我的
Runnable
实现如下所示:

public class InputHandler implements Runnable {
    @Override
    public void run() {
        boolean keepRunning = true;
        int readBytes = -1;
        byte[] readChunk = new byte[8];

        System.out.println("Starting directory observation ...");
        System.out.println("Type 'stop' to end directory observation.\n");

        while (keepRunning) {
            try {
                readBytes = System.in.read(readChunk);

                if (readBytes > 4) {
                    keepRunning &= !(new String(readChunk).contains("stop"));
                }
            } catch (Exception e) {
                System.err.println("Failed to read input!");
                keepRunning = false;
            }
        }

        System.out.println("\nDirectory observation stops now ...");
    }
}
我的主要方法是:

// Prepare the WatchService stuff ...
Thread ihThread = new Thread(new InputHandler());

do {
    WatchKey watchKey = directoryWatch.take();

    for (WatchEvent<?> event : watchKey.pollEvents()) {
        if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
            // do something
        }
    }

    keepRunning &= !Thread.State.TERMINATED.equals(ihThread.getState())
            && watchKey.reset();
} while (keepRunning);
//准备WatchService的资料。。。
Thread ihThread=新线程(new InputHandler());
做{
WatchKey WatchKey=directoryWatch.take();
for(WatchEvent事件:watchKey.pollEvents()){
if(StandardWatchEventTypes.ENTRY_CREATE.equals(event.kind())){
//做点什么
}
}
keepRunning&=!Thread.State.TERMINATED.equals(ihtread.getState())
&&watchKey.reset();
}同时(继续修剪);

当我运行代码时,不会打印任何消息,也无法在命令行中写入任何内容。如何从新线程访问'main'
系统in
系统out

我当年构建DataFetcher就是为了实现这一目的。最终,我厌倦了总是重新编写自定义线程阅读器,所以我创建了这个通用解决方案:你开始线程了吗?我在任何地方都看不到
ihtread.start()
System.in
是一个公共静态字段。你可以随时从任何方法访问它。谢谢@Codebender,我没看到