Java is a multithreaded programming language. That means that we can create a process that can be executed by multiple threads simultaneously.
What is a thread in Java?
A thread is a lightweight smallest part of a process. It can run concurrently with other threads. It is some kind of a mechanism that ensures the independent execution of a single task within a program.
Threads are sharing the same memory. Since the threads are independent, if an exception occurs in one thread, it doesn’t affect other threads.
The life cycle of a thread
During execution, the thread goes through several states. Thread can only be in one state at a time.
Thread life cycle:
- NEW – A thread that has not yet started.
- RUNNABLE – A thread executes in the Java virtual machine (JVM).
- BLOCKED – A thread is blocked
- WAITING – A thread is waiting for another thread to perform a certain action
- TIMED_WAITING – A thread that is waiting for another thread for up to a specified waiting time
- TERMINATED – A thread that has exited
Advantages of Multithreading in Java
- We can significantly speed up program execution time using multiple threads.
- If we get an exception in one thread, that will not affect the execution of other threads since threads run independently of each other.
- Using threads, we can execute multiple operations at the same time, without blocking the main thread that the user started.
How to create a Thread in Java?
We can create a thread in two ways:
- Extending Thread class
- Implementing Runnable interface
Creating a Thread by extending the Thread class
Thread class belongs to java.util package. It extends the Object class and implements the Runnable interface. Some of the methods:
- currentThread() – Returns a reference to the currently executing thread object.
- getId() – Returns the identifier of this thread.
- getName() – Returns this thread’s name.
- getPriority() – Returns this thread’s priority.
- isAlive() – Tests if this thread is alive.
- join() – Waits for this thread to finish.
- run() – If this thread was constructed using a separate Runnable object, then that Runnable object’s run method is called; otherwise, this method does nothing and returns.
- sleep() – suspend a thread for a period of time.
- start() – start a thread by calling its run() method
You can check out the official documentation of the Thread class.
Examples of creating a Thread in Java
Create a thread by extending the Thread class
public class TestMultithreading extends Thread { public void run() { System.out.println("The thread is running..."); } public static void main(String args[]) { TestMultithreading test = new TestMultithreading(); test.start(); } }
Get the id and name of a thread
public class TestMultithreading extends Thread { public void run() { System.out.println("ID: " + Thread.currentThread().getId()); System.out.println("Name: " + Thread.currentThread().getName()); System.out.println("The thread is running..."); } public static void main(String args[]) { TestMultithreading test = new TestMultithreading(); test.start(); } }
Put thread to sleep for 5 seconds
public class TestMultithreading extends Thread { public void run() { long start = System.currentTimeMillis(); try { Thread.sleep(5000); // milliseconds } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("The thread is running..."); System.out.println("Execution time: " + ((System.currentTimeMillis()) - start) + " ms"); } public static void main(String args[]) { TestMultithreading test = new TestMultithreading(); test.start(); } }
Creating a Thread by implementing a Runnable interface
We can create a thread by implementing a Runnable interface directly.
The Runnable interface is a functional interface with a single abstract method run() called when we start a thread using the start() method from the Thread class.
We need to instantiate the Thread class using its constructor, which accepts Runnable objects to create a thread.
Example
public class TestMultithreading implements Runnable { public void run() { System.out.println("The thread is running..."); } public static void main(String args[]) { TestMultithreading runnable = new TestMultithreading(); Thread threadObject = new Thread(runnable); // providing the object of a class that implements Runnable threadObject.start(); } }