Open In App

Multithreading in Java

Last Updated : 24 Feb, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.

Threads can be created by using two mechanisms : 

  1. Extending the Thread class 
  2. Implementing the Runnable Interface

Thread creation by extending the Thread class
We create a class that extends the java.lang.Thread class. This class overrides the run() method available in the Thread class. A thread begins its life inside run() method. We create an object of our new class and call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.

Java




// Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread {
    public void run()
    {
        try {
            // Displaying the thread that is running
            System.out.println(
                "Thread " + Thread.currentThread().getId()
                + " is running");
        }
        catch (Exception e) {
            // Throwing an exception
            System.out.println("Exception is caught");
        }
    }
}
 
// Main Class
public class Multithread {
    public static void main(String[] args)
    {
        int n = 8; // Number of threads
        for (int i = 0; i < n; i++) {
            MultithreadingDemo object
                = new MultithreadingDemo();
            object.start();
        }
    }
}


Output

Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running

Thread creation by implementing the Runnable Interface
We create a new class which implements java.lang.Runnable interface and override run() method. Then we instantiate a Thread object and call start() method on this object. 
 

Java




// Java code for thread creation by implementing
// the Runnable Interface
class MultithreadingDemo implements Runnable {
    public void run()
    {
        try {
            // Displaying the thread that is running
            System.out.println(
                "Thread " + Thread.currentThread().getId()
                + " is running");
        }
        catch (Exception e) {
            // Throwing an exception
            System.out.println("Exception is caught");
        }
    }
}
 
// Main Class
class Multithread {
    public static void main(String[] args)
    {
        int n = 8; // Number of threads
        for (int i = 0; i < n; i++) {
            Thread object
                = new Thread(new MultithreadingDemo());
            object.start();
        }
    }
}


Output

Thread 13 is running
Thread 11 is running
Thread 12 is running
Thread 15 is running
Thread 14 is running
Thread 18 is running
Thread 17 is running
Thread 16 is running

Thread Class vs Runnable Interface 

  1. If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple inheritance. But, if we implement the Runnable interface, our class can still extend other base classes.
  2. We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface.
  3. Using runnable will give you an object that can be shared amongst multiple threads. 

 



Previous Article
Next Article

Similar Reads

Java Multithreading Program with Example
Multithreading is a concept in which our program can do multiple tasks in a single unit of time. Thread is the execution unit of any process. Every process must have one thread and that thread name is the main thread. In this article. We will create a Java program that will do writing on file until the user gives input on the terminal. Here, We nee
4 min read
Java Multithreading - One Thread to Take Input, Another to Print on Console
Multithreading is a concept in which our program can do two or more tasks at the same time. Thread is the execution unit of any process. Every process has at least one thread which is called main thread. In this article, we will create a Java program that will do printing on the console until the user gives input. Here, we need two threads. One thr
4 min read
What does start() function do in multithreading in Java?
We have discussed that Java threads are typically created using one of the two methods : (1) Extending thread class. (2) Implementing RunnableIn both the approaches, we override the run() function, but we start a thread by calling the start() function. So why don't we directly call the overridden run() function? Why always the start function is cal
2 min read
Java Thread Priority in Multithreading
As we already know java being completely object-oriented works within a multithreading environment in which thread scheduler assigns the processor to a thread based on the priority of thread. Whenever we create a thread in Java, it always has some priority assigned to it. Priority can either be given by JVM while creating the thread or it can be gi
5 min read
Deadlock in Java Multithreading
synchronized keyword is used to make the class or method thread-safe which means only one thread can have the lock of the synchronized method and use it, other threads have to wait till the lock releases and anyone of them acquire that lock.  It is important to use if our program is running in a multi-threaded environment where two or more threads
7 min read
Java Multithreading Interview Questions and Answers
Java Multithreading is a fundamental aspect of the Java programming language, enabling developers to create applications that can perform multiple tasks simultaneously, thus improving performance and responsiveness. Java has been rated number one in TIOBE popular programming developers which are used by over 10 Million developers over 15 billion de
13 min read
MultiThreading in Android with Examples
Working on multiple tasks at the same time is Multitasking. In the same way, multiple threads running at the same time in a machine is called Multi-Threading. Technically, a thread is a unit of a process. Multiple such threads combine to form a process. This means when a process is broken, the equivalent number of threads are available. For example
3 min read
Limitations of synchronization and the uses of static synchronization in multithreading
Multithreading feature of java is the feature around which the concept revolves as it allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such a program is called a thread. So, threads are lightweight processes within a process where as we all know threads can be created by using two mechanisms
8 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
How to Convert java.sql.Date to java.util.Date in Java?
If we have the Date object of the SQL package, then we can easily convert it into an util Date object. We need to pass the getTime() method while creating the util Date object. java.util.Date utilDate = new java.util.Date(sqlDate.getTime()); It will give us util Date object. getTime() method Syntax: public long getTime() Parameters: The function do
1 min read
Article Tags :
Practice Tags :