Thread Name
In this chapter you will learn:
Thread Name
You can set the name of a thread by using setName()
.
You can obtain the name of a thread by calling getName()
.
These methods are members of the Thread
class and are declared like this:
final void setName(String threadName)
final String getName( )
Here, threadName
specifies the name of the thread.
Set thread name
The following code sets name to threads.
public class Main {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override/*from j av a2 s. c o m*/
public void run() {
String name = Thread.currentThread().getName();
int count = 0;
while (count<Integer.MAX_VALUE) {
System.out.println(name + ": " + count++);
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
}
}
}
};
Thread thdA = new Thread(r);
thdA.setName("A");
Thread thdB = new Thread(r);
thdB.setName("B");
thdA.start();
thdB.start();
}
}
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Thread