[英]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
我需要附加task#:
東西,每當被稱為System.out.println
。
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#:
ouput3
你有什么想法嗎?
我希望我的解釋足夠清楚。 提前致謝。
解決此問題的正確方法是使用類似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
變量,如果需要將更多數據與該線程關聯Thread.currentThread.getId()
獲取的特定於線程的信息。實際的日志記錄消息。
如果要顯示正在執行代碼的當前線程ID,則可以使用:
System.out.print(Thread.currentThread().getId());
我不確定您是否要顯示線程ID。
或者,您可以將值保存到線程本地變量:
ThreadLocal threadLocal = new ThreadLocal();
threadLocal.set("task#1");
String threadLocalValue = (String) threadLocal.get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.