public class GetCurrentThread implements Runnable {
Thread th;
public GetCurrentThread(String threadName) {
th = new Thread(this,threadName); //<----DOUBT
System.out.println("get threadname "+th.getName());
th.start();
}
public void run() {
System.out.println(th.getName()+" is starting.....");
System.out.println("Current thread name : " + Thread.currentThread().getName());
}
public static void main(String args[]) {
System.out.println("Current thread name : " + Thread.currentThread().getName());
new GetCurrentThread("1st Thread");
//new GetCurrentThread("2nd Thread");
}
}
Can someone explain what the 2nd line of above code is doing?
My understanding for “th = new Thread(this,threadName)” is, it will create thread object with the name given; let say name “1st Thread”.Now, What “this” keyword is doing here?because when i remove this and try get name of the thread I got the name with no issues, but it never started run().can someone explain in simple terms rather than with one single line answer. i really appreciate everyone’s help.
Your 2nd line is constructing a new
Threadobject with yourGetCurrentThreadclass as the target (this) and a thread name of"threadName". Yourthiscan be the target because it implementsRunnable. Inside of theThreadclass, when the thread is started, it callsThread.run()which does:Your
GetCurrentThreadis the target since you passthisin to the constructor. Really it should not be calledGetCurrentThreadsince it isn’t a thread. Two lines after you have constructed yourThread, you start it running:The
start()method does the actual work of creating a separate working native thread. The first thing the thread does is to call therun()method in yourGetCurrentThreadclass.As a comment, typically it is not recommended for a class to
start()itself in its constructor. There are race conditions that are inherent with this that can cause problems. It is better to have astart()method on yourGetCurrentThreadYour main would look like: