multithreading - need to understand thread(this, ThreadName) in java? -
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()+" 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 explain 2nd line of above code doing? understanding "th = new thread(this,threadname)" is, create thread object name given; let name "1st thread".now, "this" keyword doing here?because when remove , try name of thread got name no issues, never started run().can explain in simple terms rather 1 single line answer. appreciate everyone's help.
th = new thread(this, threadname); //<----doubt
your 2nd line constructing new thread
object getcurrentthread
class target (this
) , thread name of "threadname"
. this
can target because implements runnable
. inside of thread
class, when thread started, calls thread.run()
does:
public void run() { if (target != null) { target.run(); } }
your getcurrentthread
target since pass this
in constructor. should not called getcurrentthread
since isn't thread. 2 lines after have constructed thread
, start running:
th.start();
the start()
method actual work of creating separate working native thread. first thing thread call run()
method in getcurrentthread
class.
as comment, typically not recommended class start()
in constructor. there race conditions inherent can cause problems. better have start()
method on getcurrentthread
/** start underlying thread */ public void start() { th.start(); }
your main like:
public static void main(string args[]) { system.out.println("current thread name : " + thread.currentthread().getname()); getcurrentthread thread1 = new getcurrentthread("1st thread"); thread1.start(); }
Comments
Post a Comment