我编写了一个程序来运行一些线程,这些线程调用一个产生一些输出的方法。每个线程都会产生一些输出,如下所示:
a //output made by the thread 1
b //output made by the thread 2
c //output made by the thread 3
d //output made by the thread 2
e //output made by the thread 1
f //output made by the thread 3
我想以这种方式打印这个输出:
task1: a //output made by the thread 1
task2: b //output made by the thread 2
task3: c //output made by the thread 3
task2: d //output made by the thread 2
task1: e //output made by the thread 1
task3: f //output made by the thread 3
我需要在调用 System.out.println
时附加 task#:
的内容。
run()
方法是这样的:
@Override
public void run() {
long start = 0, end = 0;
start = System.currentTimeMillis();
try {
myClass.do(param1, param2); //this is the method that produce the output
} catch (IOException ex) {
ex.printStackTrace();
}
end = System.currentTimeMillis();
System.out.println("Thread time: "+ (end - start));
}
这是在 run()
中调用的方法:
@Override
public void do(String u, String p) throws IOException {
System.out.println("output1: "+ u);
System.out.println("output2: "+ p);
System.out.println("output3");
}
我希望在显示所有 ouput1
、ouput2
、ouput3
task#:
之前;你有什么想法吗?
我希望我的解释足够清楚。 提前致谢。
最佳答案
解决此问题的正确方法是使用像 java.util.logging
这样的日志记录 API 而不是 System.out
。示例:
private static final Logger LOG = Logger.getLogger(MyTestClass.class.getName());
@Override
public void do(String u, String p) throws IOException {
LOG.log(Level.INFO, "output1: "+ u);
LOG.log(Level.INFO, "output2: "+ p);
LOG.log(Level.INFO, "output3");
}
然后你可能会注册一个 ConsoleHandler
的自定义子类其中包括通过 Thread.currentThread.getId()
(或 ThreadLocal
变量,如果您需要将更多数据与线程相关联)获取的线程特定信息在打印实际的日志消息之前它自己的。
关于java - 每当调用 System.out.println 时打印任务名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44090959/