Thread
A thread is a sub-process that operates independently and concurrently with other threads within a larger process. For each thread, it is a small and lightweight unit of processing. Thread is a class defined in Java. Lang package is implicitly inherited in all the user-defined and predefined classes in Java.
Key Point
- Thread class specifies three main properties i.e. ID, name, and priority.
- Thread class has overloaded constructors.
- We can create Thread in two ways.
1. By extending the Thread class
2. By implementing the Runnable interface
2. By implementing the Runnable interface
- It is a smallest unit of execution in a program.
1. Creating Thread by Extending the Thread Class
Example:
package quipoin;
class Demo extends Thread {
public void run() {
System.out.println("Thread is running!!");
}
public static void main(String args[]) {
Demo t1 = new Demo();
t1.start();
}
}
Output:
Thread is running!!
2. Creating Thread by Implementing Runnable Interface
Runnable Interface is present in the java .lang package and it has only one method public void run().
Example:
package quipoin;
class Sample implements Runnable {
public void run() {
System.out.println("Thread is running!!");
}
public static void main(String args[]) {
Sample m1 = new Sample();
Thread t1 = new Thread(m1); // Using the constructor Thread(Runnable r)
t1.start();
}
}
Output:
Thread is running!!
Thread Properties
1. Thread Id
- It is a unique integer number that is used to identify thread class instances created in JVM.
- Thread Id is initialized at the time of object creation automatically. We cannot change the Id of a Thread.
2. Thread Name
- It is a String type used to set the name of a thread.
t1.setName("MyThread");
System.out.println(t1.getName());
- For every thread created in JVM default name is initialized user can provide the name of a thread and can change it.
3. Thread Priority
- Thread priority is a number that is used to define the priority of a thread.
- JVM executes the thread based on the thread priority.
- The priority ranges from 1(low priority) to 10(high priority).
- If the user is not defining the priority of a thread then the default priority is 5(mid).
Feature | Extending Thread Class | Implementing Runnable Interface |
---|---|---|
Inheritance | Not possible to extend another class | Allows multiple inheritance |
Memory Usage | Creates separate memory for each thread | Uses shared memory |
Flexibility | Less flexible | More flexible and scalable |
Recommended For | Simple threading tasks | Complex application |