在多线程Java程序中,每个线程都有自己的System.out副本吗? [英] In a multithreaded Java program, does each thread have its own copy of System.out?

查看:170
本文介绍了在多线程Java程序中,每个线程都有自己的System.out副本吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个多线程Java程序,其中每个线程可能需要将其标准输出重定向到单独的文件。每个线程都有自己的文件。可以在每个线程的基础上重定向System.out,还是可以在所有线程上更改System.out全局?

I'm writing a multithreaded Java program where each thread potentially needs its standard output redirected to a separate file. Each thread would have its own file. Is it possible to redirect System.out on a "per-thread" basis or are changes to System.out global across all threads?

推荐答案


是否可以在每个线程的基础上重定向System.out

Is it possible to redirect System.out on a "per-thread" basis

否这不可能。 System.out 是静态的,当JVM最初启动时,每个JVM都有一个作为系统类加载器的一部分加载。虽然建议每个线程使用正确的日志记录调用,但我认为有理由不能这样做。可能是第三方库或其他代码就是以这种方式使用 System.out

No it is not possible. System.out is static and there is one per JVM that is loaded as part of the system classloader when the JVM initially boots. Although of course using proper logging calls per-thread is recommend, I assume there are reasons why you can't do this. Probably a 3rd party library or other code is what is using System.out in this manner.

有一件事你可以做(作为一个激进的建议)是制作你自己的 PrintStream 委托给 ThreadLocal< PrintStream> 。但是你需要 @Override 你的应用程序调用的相应方法才能让它按线程运行。

One thing you could do (as a radical suggestion) is to make your own PrintStream that delegates to a ThreadLocal<PrintStream>. But you will need to @Override the appropriate methods called by your application to get it to work per-thread.

最后,如果你因为担心并发而问这个, System.out 是一个 PrintStream 所以它是已经已同步,可供多个线程安全使用。

Lastly, if you are asking this because you are worried about concurrency, System.out is a PrintStream so it is already synchronized under the covers and can be used safely by multiple threads.

这篇关于在多线程Java程序中,每个线程都有自己的System.out副本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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