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

Print task name whenever System.out.println is called

我写了一个程序,它运行一些线程,调用一个产生一些输出的方法。每个线程都有一些输出,像这样:

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#:;你有什么想法吗?

希望我的解释足够清楚。 提前致谢。

如果你想显示当前正在执行代码的线程ID,你可以使用:

System.out.print(Thread.currentThread().getId());

我不确定你是否要显示线程 ID。

或者您可以将值保存到线程局部变量:

ThreadLocal threadLocal = new ThreadLocal();
threadLocal.set("task#1");
String threadLocalValue = (String) threadLocal.get();

解决这个问题的正确方法是使用像 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 变量,如果你需要关联更多数据与线程)在打印实际日志消息之前自行处理。