Java Program to Create a Thread
Thread can be referred to as a lightweight process. Thread uses fewer resources to create and exist in the process; thread shares process resources. The main thread of Java is the thread that is started when the program starts. The slave thread is created as a result of the main thread. This is the last thread to complete execution.
A thread can programmatically be created by:
- Implementing the java.lang.Runnable interface.
- Extending the java.lang.Thread class.
You can create threads by implementing the runnable interface and overriding the run() method. Then, you can create a thread object and call the start() method.
The Thread class provides constructors and methods for creating and operating on threads. The thread extends the Object and implements the Runnable interface.
// start a newly created thread. // Thread moves from new state to runnable state // When it gets a chance, executes the target run() method public void start()
Any class with instances that are intended to be executed by a thread should implement the Runnable interface. The Runnable interface has only one method, which is called run().
// Thread action is performed public void run()
Benefits of creating threads :
- When compared to processes, Java Threads are more lightweight; it takes less time and resources to create a thread.
- Threads share the data and code of their parent process.
- Thread communication is simpler than process communication.
- Context switching between threads is usually cheaper than switching between processes.
Calling run() instead of start()
The common mistake is starting a thread using run() instead of start() method.
Thread myThread = new Thread(MyRunnable()); myThread.run(); //should be start();
The run() method is not called by the thread you created. Instead, it is called by the thread that created the myThread.
Example 1: By using Thread Class
Welcome to GeeksforGeeks.
Example 2: By implementing Runnable interface
gfg Inside run method
Please Login to comment...