Thread Names
When you create a Java thread you can give it a name. The name can help you distinguish different threads from each other. For instance, if multiple threads write toSystem.out
it can be handy to see which thread wrote the text. Here is an example:
Thread thread = new Thread("New Thread") { public void run(){ System.out.println("run by: " + getName()); } }; thread.start(); System.out.println(thread.getName());Notice the string "New Thread" passed as parameter to the
Thread
constructor. This string is the name of the thread. The name
can be obtained via the Thread
's getName()
method. You can also
pass a name to a Thread
when using a Runnable
implementation. Here
is how that looks:
MyRunnable runnable = new MyRunnable(); Thread thread = new Thread(runnable, "New Thread"); thread.start(); System.out.println(thread.getName());Notice however, that since the
MyRunnable
class is not a subclass of
Thread
, it does not have access to the getName() method of the thread
executing it. For example, you can't do it like this:
Runnable r = new Runnable(){ public void run(){ System.out.println( getName() + " running"); // you can't call getName() method here }; };
Thread.currentThread()
TheThread.currentThread()
method returns a reference to the Thread
instance executing
currentThread()
. This way you can get access to the Java Thread
object representing
the thread executing a given block of code. Here is an example of how to use Thread.currentThread()
:
Thread thread = Thread.currentThread();Once you have a reference to the
Thread
object, you can call methods on it. For instance, you can get
the name of the thread currently executing the code like this:
String threadName = Thread.currentThread().getName();
but you can get thread name like this:
Runnable r = new Runnable(){ public void run(){ System.out.println(Thread.currentThread().getName() + " running"); // but you can get thread name like this }; };
@reference_1_tutorials.jenkov.com
Creating and Starting Java Threads
No comments:
Post a Comment