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

时间:2017-05-20 21:26:16

标签: 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

每当被称为task#:时,我都需要附加System.out.println的内容。

run() mehtod是这样的:

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

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

3 个答案:

答案 0 :(得分:2)

正确的方法是使用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变量获取的特定于线程的信息,如果您需要关联更多数据在打印实际的日志消息之前,单独使用该线程。

答案 1 :(得分:1)

如果要显示正在执行代码的当前线程ID,请使用:

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

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

答案 2 :(得分:1)

或者您可以为线程本地保存价值:

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