java - 每当调用 System.out.println 时打印任务名称

标签 java multithreading multitasking

我编写了一个程序来运行一些线程,这些线程调用一个产生一些输出的方法。每个线程都会产生一些输出,如下所示:

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");
}

我希望在显示所有 ouput1ouput2ouput3 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/

相关文章:

c# - 如何使用 NUnit 在 C# 中对线程安全通用列表进行单元测试?

java - 网络/数据库作业的足够线程数

objective-c - 'applicationDidBecomeActive' 之后调用了什么方法?

Java - 使用 Accessor 和 Mutator 方法

java - 如何将列表/ map 与组合框一起使用

java - Gradle深度讲解中的build-by-convention是什么?

Python如何批量处理多线程?

java - 无法在 Android 中使用 SimpleDateFormat 解析 MYSQL 时间戳

c# - C# 中各种线程同步选项之间有什么区别?

iPhone - 应用程序在后台运行时更改应用程序设置