You are here:

Java/2-what is the use of thread class constructors

Advertisement


Question
Hi !last time I asked one doubt with heading “what is the use of thread class constructors”.But I could not ask that doubt in a right
manner.Now I am asking the same doubt in a simple and clear manner.My doubt is on Thread class constructors. My doubts based on below simple code.
In below code ,in main method there is a statement as ” Thread C4=new Thread (new first(),"FIRSTTHREAD");”
This Statement Will create a Thread FIRSTTHREAD for the class “first”.
Here we used Thread class constructor public Thread(Runnable target,String name);
There are some other constructors in Thread class like
1)public Thread();
2)public Thread(String name);
The first constructor is used to create an object of Thread class.
The second constructor is used to create an object of Thread class but with required name.
Then my question is
-->What is the benefit of creating object to thread class?
-->A class named with” four” is available in below code.By using second constructor of above constructors is it possible to write “four f1=new four(“MYTHREAD”);”
---------------------------------------------
class first implements Runnable
  {  
  public void run()
  {  
  System.out.println(Thread.currentThread().getName());
  }  
  }  
  class four extends Thread  
  {  
 public void run()
 {  
 System.out.println(Thread.currentThread().getName());
 }
 }
 class Third  
 {
 public static void main(String args[])  
 {  

Thread C4=new Thread (new first(),"FirstThread");
C4.start();

}  
}

Output:  

FirstThread

Answer
1. Creating a thread allows you to run multiple pieces of code at the same time. This can use multiple processors, or can allow one thread to continue while another one is waiting on a response or resource.
2. The reason to use a thread constructor with a string argument is to make it easier to diagnose which thread is doing what. For example if you are using a debugger you can see the name of each string. Also, if you are using windows you can use control-break (or control-\ in linux/mac) in the console to see a stack trace of all threads.

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


Artemus Harper

Expertise

I have a Masters in computer science. I can answer questions on core J2SE, swing and graphics. Please no questions about JSP or J2ME.

Experience

I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection. Some experience in bio-informatics. Basics in c++ and c#

Organizations
Washington State University

Education/Credentials
MS in Computer Science from Washington State University and a BS in Mathematics and Computer Science from Central Washington University.

©2016 About.com. All rights reserved.