同步和System.out.println [英] Synchronization and System.out.println

查看:135
本文介绍了同步和System.out.println的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果多个线程在没有同步的情况下调用System.out.println(String),输出是否可以交错? API 没有提及同步,所以这似乎是可能的,或者是缓冲和/或VM内存模型等阻止了交错输出?

If multiple threads call System.out.println(String) without synchronization, can the output get interleaved? The API makes no mention of synchronization, so this seems possible, or is interleaved output prevented by buffering and/or the VM memory model, etc.?

编辑:

例如,如果每个线程包含:

For example, if each thread contains:

System.out.println("ABC");

输出保证为:

ABC
ABC

或者可能是:

AABC
BC


推荐答案

由于API文档未在 System.out object PrintStream# println(String)方法 你不能认为它是线程安全的

Since the API documentation makes no mention of thread safety on the System.out object nor does the PrintStream#println(String) method you cannot assume that it is thread-safe.

但是,完全可能的是,特定JVM的底层实现使用 println 方法的线程安全函数(例如 printf on gl ibc )实际上,根据你的第一个例子,输出将得到保证(总是 ABC \ n 然后 ABC \ n ,你的第二个例子中没有穿插角色)。但请记住,有许多JVM实现,只需遵守JVM规范,而不是该规范之外的任何约定。

However, it is entirely possible that the underlying implementation of a particular JVM uses a thread-safe function for the println method (e.g. printf on glibc) so that, in reality, the output will be guaranteed per your first example (always ABC\n then ABC\n, never interspersed characters per your second example). But keep in mind that there are lots of JVM implementations and they are only required to adhere to the JVM specification, not any conventions outside of that spec.

如果你绝对必须确保没有println调用会在您描述时散布,然后您必须手动强制执行互斥,例如:

If you absolutely must ensure that no println calls will intersperse as you describe then you must enforce mutual exclusion manually, for example:

public void safePrintln(String s) {
  synchronized (System.out) {
    System.out.println(s);
  }
}

当然,这个例子只是一个例子,应该是不能被视为解决方案;还有许多其他因素需要考虑。例如,上面的 safePrintln(...)方法只有在所有代码使用该方法且没有任何调用时才是安全的。 System.out.println(...)直接。

Of course, this example is only an illustration and should not be taken as a "solution"; there are many other factors to consider. For example, the safePrintln(...) method above is only safe if all code uses that method and nothing calls System.out.println(...) directly.

这篇关于同步和System.out.println的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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