简体   繁体   English

从StdIn读取并同时写入StdOut是否安全?

[英]Is it safe to read from StdIn and write to StdOut concurrently?

Here's the code: 这是代码:

public static void main(String[] args) throws InterruptedException {
    Thread t = new Thread(new Runnable() {
        public void run() {
            while(true){
                BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in));
                try {
                    System.out.println(buffer.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    t.start();
    while(true){
        System.out.println("Text");
        Thread.sleep(1000);
    }
}

I'm not quite sure if it's actually safe to do so. 我不确定这样做是否真的安全。 Can some cucncurrency bug arise in such code? 此类代码中会出现一些货币错误吗? I ran a couple of tests and it works pretty fine, but who knows how it will behave after 1000000 attempts... 我进行了几次测试,效果很好,但是谁知道在经过1000000次尝试后它将如何运行...

Yes, it's safe. 是的,这很安全。 If you look at the implementation for println , you'll see that the code is synchronized : 如果查看println的实现,您将看到代码已synchronized

public void println(String x) {
    synchronized (this) {
        print(x);
        newLine();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM