Multiple Thread using Thread class & Runnable Interface
- Thread Class:
- Syntax: public class Thread extends Object implements Runnable
- Usage:
- The JVM allows an application to have multiple threads of execution running concurrently or parallel.
- Every thread has higher, normal or lower priority.
- Threads with higher priority are executed first than lower priority.
- Each thread may be daemon or non-daemon.
- When a JVM starts up, there is a single non-daemon thread.
- The JVM continues to execute threads until either of the following occurs:
- The exit method of class Runtime has been called.
- All threads that are not daemon threads have died.
- There are two ways to create a new thread of execution.
- One is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread. An instance of the subclass can then be allocated and started.
- The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started.
- Every thread has a name for identification purposes.
- More than one thread may have the same name.
- If a name is not specified when a thread is created, a new name is generated for it.
- Threads can be created by using two mechanisms :
- 1. Extending the Thread class
- 2. Implementing the Runnable Interface
- 1. Thread using Thread Class:
- To declare a class that is sub-class of the class Thread defined in java.lang package.
- Output-01:
[Output of Thread extend program] - Program-01:
[Program: ExtendThreadExample.java] - Output-2:
[Output of Thread extend program] - Program-2:
[Program: MultiThread.java] - 2. Thread using Runnable Class:
[Extends Thread skeleton] |
Tags:
Java