Thread
What are Threads in Java?
- You can think of a thread as 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 Points:
- 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:
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. 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.
- 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).