This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Hi!My doubt is on Thread class constructors
2)public Thread(String name)
The above two are two constructors of thread class.
First constructor is used to create object of thread class.
Second constructor is also used to create object of thread class with required name.
If we write
1)Thread t1=new Thread();
This creates a thread class object t1.
This also creates Thread class object t2 .It also creates thread with name "MYTHREAD".
My questions are
1)What is the benefit of above t1,t2;
2)How can we use the thread class objects t1,t2?
3)Is it possible to execute run method of the thread "MYMTHREAD"?
4)Suppose we have extended class named “a” from Thread class like below.
Then how can we use t1,t2 on below class “a”?
Is it possible to create thread to below class “a” with required name by using above constructors?
Since you have asked too many questions at once let me introduce you to the answers in the same manner.
Ans 1: Both t1 and t2 are valid Thread Objects, only one has a decided name and other doesn't. Both run in the same manner as any other thread.
Ans 2: You can use both the objects in a variety of ways as per the requirement in your project.
Ans 3: yes it is possible to execute run() of the Thread 'MYTHREAD" using t2.start();
Ans 4: Since class a extends Thread it itself "is a" Thread now. You can have a run() in your Class "a" which will be called on any object of the type "a"
Ans 5: yes it is possible to create a thread with a required name using the second constructor you mentioned i.e. new Thread(String name);
And yes, your class should start with a CAPITAL Letter and also access specifiers work only when in "small" letters your one is incorrect.
Note, however, that you will probably never have a good reason to extend thread. You're not creating a specialized type of Thread. You're just creating a task to be executed, so you should implement Runnable instead.