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

查看:28
本文介绍了在多线程 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 最初启动时作为系统类加载器的一部分加载.尽管当然建议使用每个线程正确的日志记录调用,但我认为有些原因您不能这样做.可能是第 3 方库或其他代码以这种方式使用 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.但是您需要@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 所以它已经在 synchronized 下封面,可以安全使用多个线程.

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天全站免登陆