【问题标题】:Print task name whenever System.out.println is called每当调用 System.out.println 时打印任务名称
【发布时间】:2017-10-20 19:38:19
【问题描述】:

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

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

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

【问题讨论】:

  • 你能分享一些代码吗?如果没有上下文,很难为您提供帮助。
  • @Mureinik 感谢您的评论,我更新了我的问题。

标签: java multithreading multitasking


【解决方案1】:

解决此问题的正确方法是使用 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 变量,如果您需要将更多数据与线程相关联)获取的特定于线程的信息。在打印实际的日志消息之前拥有。

【讨论】:

  • 谢谢,如果您认为我的问题有用,请投票给我
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

    或者您可以将值保存到线程本地:

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

    【讨论】:

      猜你喜欢
      • 2015-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-17
      • 2017-12-05
      • 1970-01-01
      • 2018-03-26
      相关资源
      最近更新 更多