Constructors-and-Methods
Thread class constructors
- The thread class has overloaded constructors the few important constructors are
No-argument constructor:
- Thread t1=new Thread();
- The Thread class was created with the default values of thread properties.
String-argument constructor:
- Thread t1=new Thread("java");
- Creates a Thread class instance where the thread name will be java. Thread Id and thread priority will get default initialization.
Runnable-argument type constructor:
- Thread t1=new Thread(r1);
- Let's say ‘r1’ be the object of the Runnable Interface;
Two-argument constructor:
- Thread t1=new Thread(r1,"Quipo");
- Creates the thread class instance with the specified runnable type and specified Thread name.
- The first argument is the Runnable type and the second argument is the String type.
Thread class methods
Thread class provides various methods as follows:
1. public int getId();
- By invoking this method it receives the ID of Thread.
2. public String getName();
- By invoking this method it receives the name of a Thread.
3. public int getPriority();
- This method returns the priority number of a Thread.
4. public void setName(String name);
- This method is used to set the name of a Thread.
5. public void setPriority(int priorityNum);
- This method is used to set the priority of a Thread.
6. public void start();
- On invoking this method it starts execution of a Thread.
- the start() internally calls the run method of a thread object.
7. public void run();
- The thread execution begins by calling run().
8. public void stop();
- The method is used to stop the running thread, on invoking this method the running Thread will be terminated.
9. public static void sleep(long time);
- On invoking this method it pauses the currently running thread for a specified period of time once the time elapsed the thread resumes the execution.
Example for sleep():
package quipoin;
public class Sample extends Thread{
public void run(){
System.out.println("Printing even numbers from 1-10");
for(int i=1;i<=10;i++){
if(i%2==0){
System.out.print(i+" ");
}
try{
Thread.sleep(1000);
}
catch(InterruptedException e){
e.printStackTrace();
}
}
}
public static void main(String[] args) {
System.out.println("Main method started");
Sample sample=new Sample();
sample.start();
}
}
Output:
Main method started
2 4 6 8 10
- On invoking start() on a thread, the thread is registered to the thread scheduler of JVM once JVM allocates a new stack it calls the run() method to do execution on the new stack.
- If we directly invoke the run() instead of start() the execution happens on the current stack which will not allow achieving parallel execution.