Threads
Threads is a thread of execution in a program. It’s lightweight process and has an individual stack. There is one call stack per thread. If you don’t create any thread in a program, there are threads they will be running back. The main() method runs on one thread called main thread.
Thread can be instantiated in two ways
- Extend java.lang.Thread
- Implement Runnable interface
Defining a Thread
Thread can be defined in two ways.
1) Extending java.lang.Thread
Extend the java.lang.Thread and override run() method.
1 2 3 4 5 6 7 |
class ThreadDemo extends Thread { public void run() { System.out.println("Thread is running"); } } |
2 ) Implementing java.lang.Runnable
Implement Runnable interface and give implementation for run() method in your class
1 2 3 4 5 6 7 |
class RunnableDemo implements Runnable { public void run() { System.out.println("Thread is running in runnable"); } } |
It is always better to implement a Runnable interface than to extend a Thread because
Java doesn’t support multiple inheritance and if you extend Thread class, you can’t extend anything else. Implementing an interface is more flexible and can be inherited another class.
Instantiating a Thread
Every thread of execution begins as an instance of class Thread, regardless of your run() method is in Thread class or Runnable interface.
If your class extends Thread class, then instantiating done as:
ThreadDemo t = new ThreadDemo();
If your class implements Runnable interface, instantiating done in two step:
First instantiate your Runnable class:
RunnableDemo r = new RunnableDemo();
Then get instance of java.lang.Thread
Thread t = new Thread(r);
A thread in java is an instance of java.lang.Thread. Thread class contains the method for managing the threads includes creating, starting and pausing them. Methods are :
- run()
- start()
- sleep()
- yield()
- join()
run() method
The action happens in the run() method. The code that’s to be run in a separate thread write it in run() method. The thread of execution always begins by invoking run() method. After the run() method completes, thread is considered as dead.
start() method
To get a thread in a new call stack, you need to start the thread. When thread is instantiated but not started, thread is in new state. Once start() method has been called thread is said to be alive and it moves from new state to runnable state. If you call start() second time on a thread, it will throw IllegalThreadStateException, which is a RuntimeException.
Following example shows defining, instantiating and starting the thread.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class RunnableDemo implements Runnable { public void run() { for(int i = 1; i < 6; i++) { System.out.println("Runnable running"); } } } public class ThreadsDemo { public static void main (String [] args) { RunnableDemo r = new RunnableDemo(); Thread t = new Thread(r); t.start(); } } |
Output:
Runnable running
Runnable running
Runnable running
Runnable running
Runnable running
Threads Life Cycle
There are five states in threads life cycle.
New – In this state thread is not considered to be alive. This is the state when thread is instantiated but still start() method is not called.
Runnable – The thread first comes to runnable state when start() method is invoked. In this state thread is eligible to run and it considered as alive. A thread can return to runnable state either from running, sleeping or blocked state.
Running – The scheduler selects the thread from runnable pool to run and to execute the job. After running thread can be either go to sleep, blocked or dead.
Waiting/Blocked/Sleeping – In these states thread considered to be alive but not eligible to run. From these state thread can move to runnable and can become eligible to run. A thread may be blocked because resource is not available; when resource gets available thread goes to runnable state.
A thread may be waiting because it has been asked to wait until it get notification from another thread that it may no longer to wait and can move to runnable state.
A thread may be sleeping because it is asked to go to sleep for some time and it returns to runnable when time has expired.
Dead – When thread completes run() method, it is considered to be dead. Once thread dead, it cannot be brought back to live.
Preventing Thread Execution
sleep() method
The sleep() method is a static method of Thread class. It is used to slow down the thread by asking it to go into sleep for specified time before coming back to runnable. The sleep() method can throw InterruptedException so try/catch is used to handle exception.
try {
Thread.sleep(10000); //sleeps for 1 sec
} catch(InterruptedException ex) { }
yield() method
It is a static method of Thread class. The yield() method is used to move currently running thread back to runnable to allow the other threads of the same priority to get their turn to run.
join() method
It’s a non-static method of Thread class and lets to join one thread onto the end of another thread. If there is a thread B which cannot complete until thread A completes its work, then you can join thread B to thread A. Means thread B will not become runnable until thread A completes its work.
Thread t = new Thread()
t. start();
t.join();
Multiple Threads
Lets understand how to create multiple threads with the following example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
class MultiRunnable implements Runnable { public void run() { for (int x = 1; x <= 3; x++) { System.out.println("Run by " + Thread.currentThread().getName()+ ", x is " + x); } } } public class ThreadNames { public static void main(String [] args) { MultiRunnable r = new MultiRunnable(); Thread one = new Thread(r); Thread two = new Thread(r); Thread three = new Thread(r); one.setName("Jay"); two.setName("Ram"); three.setName("Sam"); one.start(); two.start(); three.start(); } } |
Output:
Jay
Ram
Sam
Leave a Reply