It's very useful while debugging or while viewing our log files when we have the thread namea in the log messages. It's especially useful in a multi-threaded application.
public class Main {
public static void main(String[] args) {
// Let's see the main thread's name.
System.out.println("We are currently in: "
+ Thread.currentThread().getName());
Thread thread = new Thread() {
public void run() {
String currentThreadName = Thread.currentThread().getName();
for (int i = 0; i < 5; i++) {
// Printing the user thread's name.
System.out.println("We are currently in: "
+ currentThreadName);
}
}
};
// Setting a name for our user thread.
thread.setName("MyUserThread");
thread.start();
// We're back in the main thread, let's check it.
System.out.println("We are currently in: "
+ Thread.currentThread().getName());
}
}
So, let's all give our Threads a meaningful name :-)
0 comments:
Post a Comment