BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Multithreading in java with examples

Last Updated: November 30, 2024 by Chaitanya Singh | Filed Under: java

Multithreading is one of the most popular feature of Java programming language as it allows the concurrent execution of two or more parts of a program. Concurrent execution means two or more parts of the program are executing at the same time, this maximizes the CPU utilization and gives you better performance. These parts of the program are called threads.

Threads are independent because they all have separate path of execution that’s the reason if an exception occurs in one thread, it doesn’t affect the execution of other threads. All threads of a process share the common memory. The process of executing multiple threads simultaneously is known as multithreading.

Advantages of Multithreading

  • Efficient CPU Utilization: As more than one threads run independently, this allows the CPU to perform multiple tasks simultaneously.
  • Improved Performance
  • Better Resource Sharing: As discussed earlier, threads share common memory, this reduces overhead compared to processes.

Creating Threads in Java

There are two primary ways to create threads:

1. By Extending the Thread Class

class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
}

public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // Starts the thread and executes the `run` method
}
}

2. By Implementing the Runnable Interface

class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running...");
}
}

public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread t1 = new Thread(runnable);
t1.start(); // Starts the thread and executes the `run` method
}
}

Thread Methods

  • start(): Starts the thread, calling its run() method.
  • run(): Defines the code executed by the thread.
  • sleep(milliseconds): Pauses the thread for a specified duration.
  • join(): Waits for a thread to finish before continuing.
  • isAlive(): Checks if the thread is still running.
  • getName() and setName(String name): To retrieve or set a thread’s name.

Thread Synchronization

  • Multithreading introduces asynchronous behaviour to the programs. If a thread is writing some data another thread may be reading the same data at that time. This may bring inconsistency.
  • When two or more threads need access to a shared resource there should be some way that the resource will be used only by one resource at a time. The process to achieve this is called synchronization.
  • To implement the synchronous behavior java has synchronous method. Once a thread is inside a synchronized method, no other thread can call any other synchronized method on the same object. All the other threads then wait until the first thread come out of the synchronized block.

When multiple threads access shared resources, synchronization ensures data consistency:

class Counter {
private int count = 0;

public synchronized void increment() {
count++;
}

public int getCount() {
return count;
}
}

public class Main {
public static void main(String[] args) {
Counter counter = new Counter();

Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});

Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});

t1.start();
t2.start();

try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Count: " + counter.getCount());
}
}

Thread Lifecycle

A thread in Java goes through the following states:

  1. New: When a thread object is created. A thread that has not yet started is in this state.
  2. Runnable: After calling start(), the thread is ready to run.
  3. Running: The thread is executing its run() method. A thread executing in the Java virtual machine is in this state.
  4. Blocked/Waiting: The thread is waiting for a resource or signal. A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
  5. Timed Waiting: A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
  6. Terminated: The thread finishes execution.

Read more about thread states here: Life cycle of threads

Example: Multithreading in Action

class Task1 extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Task 1 - Count: " + i);
}
}
}

class Task2 extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Task 2 - Count: " + i);
}
}
}

public class Main {
public static void main(String[] args) {
Task1 t1 = new Task1();
Task2 t2 = new Task2();

t1.start();
t2.start();
}
}

In this example, Task1 and Task2 run concurrently, and their outputs will interleave based on thread scheduling.


Key Points

  • Multithreading is not deterministic; thread execution order may vary.
  • Proper synchronization is crucial for handling shared resources to avoid race conditions.
  • Java provides the Executor framework for managing thread pools and improving scalability.

If you’d like, I can provide additional details on advanced multithreading concepts like thread pools, Callable, Future, or synchronized blocks.

Multitasking vs Multithreading vs Multiprocessing vs parallel processing

If you are new to java you may get confused among these terms as they are used quite frequently when we discuss multithreading. Let’s talk about them in brief.

Multitasking: Ability to execute more than one task at the same time is known as multitasking.

Multithreading: We already discussed about it. It is a process of executing multiple threads simultaneously. Multithreading is also known as Thread-based Multitasking.

Multiprocessing: It is same as multitasking, however in multiprocessing more than one CPUs are involved. On the other hand one CPU is involved in multitasking.

Parallel Processing: It refers to the utilization of multiple CPUs in a single computer system.

Thread priorities

  • Thread priorities are the integers which decide how one thread should be treated with respect to the others.
  • Thread priority decides when to switch from one running thread to another, process is called context switching
  • A thread can voluntarily release control and the highest priority thread that is ready to run is given the CPU.
  • A thread can be preempted by a higher priority thread no matter what the lower priority thread is doing. Whenever a higher priority thread wants to run it does.
  • To set the priority of the thread setPriority() method is used which is a method of the class Thread Class.
  • In place of defining the priority in integers, we can use MIN_PRIORITY, NORM_PRIORITY or MAX_PRIORITY.

Methods: isAlive() and join()

  • In all the practical situations main thread should finish last else other threads which have spawned from the main thread will also finish.
  • To know whether the thread has finished we can call isAlive() on the thread which returns true if the thread is not finished.
  • Another way to achieve this by using join() method, this method when called from the parent thread makes parent thread wait till child thread terminates.
  • These methods are defined in the Thread class.
  • We have used isAlive() method in the above examples too.

Inter-thread Communication

We have few methods through which java threads can communicate with each other. These methods are wait(), notify(), notifyAll(). All these methods can only be called from within a synchronized method.
1) To understand synchronization java has a concept of monitor. Monitor can be thought of as a box which can hold only one thread. Once a thread enters the monitor all the other threads have to wait until that thread exits the monitor.
2) wait()  tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify().
3) notify() wakes up the first thread that called wait() on the same object.
notifyAll() wakes up all the threads that called wait() on the same object. The highest priority thread will run first.

Top Related Articles:

  1. StringJoiner toString() Method in Java
  2. Basics: All about Java threads
  3. Constructor Overloading in Java with examples
  4. What is the difference between a process and a thread in Java?
  5. Cloneable Interface in Java – Object Cloning

Tags: Java-Multithreading

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. vinod says

    July 14, 2014 at 3:18 PM

    hi
    i am not understanding the concept of Example program 2.
    can you please explain about this.

    thank you

    Reply
    • jugal says

      July 30, 2014 at 2:59 PM

      in second example : thread is creating by extend the thread keyword. This will create new thread class .Now your Count class working as thread as in above.

      Reply
    • maha says

      October 27, 2015 at 8:27 PM

      plz explain this line of code :
      super(“my extending thread”);
      plz explain in detail why the super keyword is doing here ????????????

      Reply
      • Aki says

        January 23, 2016 at 11:43 AM

        because it is use to differentiate the base class method from child class method :)

        Reply
        • Gaurav says

          November 24, 2016 at 6:36 AM

          Basically super keyword refer to the Base class. super always will give priority to the base class.

          Reply
      • Yaser says

        August 29, 2016 at 11:10 AM

        super(“my extending thread”); will call the superclass’s constructor from extending class. So it invokes Thread(“my extending thread”);

        Reply
      • Rohith says

        October 12, 2016 at 6:58 AM

        We are calling base class constructor with parameter “my extending thread” in the super class

        Reply
  2. jugal says

    July 30, 2014 at 2:35 PM

    see proper concept.

    Reply
  3. Stephen says

    September 8, 2014 at 6:26 AM

    I can’t understand the concept of run() and start() method.

    Reply
    • DArshit says

      August 28, 2015 at 9:42 AM

      Hey Stephen whenever you will start thread by .start() method it will then first execute its run() method of that thread .

      Reply
      • abhay says

        February 3, 2017 at 12:28 AM

        Basically run is a method in thread class.
        And whenever we call .star() it will override the run() from thread class

        Reply
    • Sunita says

      August 3, 2016 at 5:31 AM

      start() is used to start the execution of the code written in run(). If you will omit start() the code inside run() will not be executed.

      Reply
    • Rajneesh says

      May 3, 2017 at 11:54 AM

      if you create a thread and you simply use run() method then it will run on the main thread but if you do use start() then the thread will not run in the main thread.

      Reply
  4. anu says

    November 8, 2014 at 4:58 AM

    I cant get what is the difference between creating thread class & implementating runnable interface?

    Reply
    • Chaitanya Singh says

      November 15, 2014 at 8:09 AM

      There is no difference. It all depends on the need and requirements. Let me explain this to you with an example.
      Java doesn’t support multiple inheritance, which means you can only extend (inherit) one class so once you extend the Thread class you cannot extend or inherit another class in Java. As per object oriented programing(OOPs), the whole purpose of inheritance is to add new functionality, modifying or improving behaviors by overriding methods of parent class. If we are not making any modification on Thread then using Runnable interface should be your choice instead of extending Thread class. There are few more things to discuss regarding this. I will cover them in detail in a separate post. I hope this makes sense now.

      Reply
      • Smith says

        January 6, 2015 at 8:39 PM

        Thanks I will love to be a friend

        Reply
  5. Bhushan says

    January 27, 2015 at 7:20 AM

    how can we execute multiple threads in parallel? if i want to access two/more files at the same time to minimize execution time ?

    Reply
    • Roshan Singh says

      April 15, 2015 at 6:40 AM

      Threads do not run absolute concurrent way but they overlap to minimize CPU wastage…..

      Reply
  6. moni says

    July 24, 2015 at 8:34 AM

    i want to know the types of multithreading in java

    Reply
  7. vinoth says

    July 28, 2015 at 4:21 PM

    Can any one explain me about Thread Pool concept?

    Reply
    • Joe says

      October 12, 2015 at 4:56 PM

      Take a look at: http://stackoverflow.com/questions/8767527/how-to-use-thread-pool-concept-in-java

      Reply
    • sai says

      October 15, 2015 at 7:47 AM

      Java Thread pool represents a group of worker threads that are waiting for the job and reuse many times.
      In case of thread pool, a group of fixed size threads are created. A thread from the thread pool is pulled out and assigned a job by the service provider. After completion of the job, thread is contained in the thread pool again.
      Advantage of Java Thread Pool:
      Better performance It saves time because there is no need to create new thread.

      Reply
  8. shahid malik says

    November 17, 2015 at 10:50 AM

    Suppose there are two files in the system containing some textual data, your program should read
    these files concurrently and merge them into one file using JAVA threads. The file should be merged
    in such a way that it contains one line of first file and one line of second file.

    Reply
  9. Philip Fasan says

    December 8, 2015 at 8:42 AM

    Do you offer pdf versions of this material? This can help when the network is not performing.

    Reply
  10. ujwala says

    February 5, 2016 at 2:24 PM

    i want know the thread class and runable class

    Reply
  11. Lalit Kumar says

    February 15, 2016 at 5:07 AM

    Hi brother, I have been going though all your post. From my point of view this the best website to learn anything from zero. Keep posting new stuffs.

    Reply
  12. Mitul Thesiya says

    March 1, 2016 at 6:22 AM

    I’m running TestNG mechanism to run parallel thread for executing my testcases. Here, i.e. for 3 parallel threads, if suppose 2nd thread is caught by any error and need to suspend till execution of remaining 2 parallel threads, could you guide how can I achieve to facilitate and support TestNG valid mechanism for parallel testing in this case?

    Reply
  13. Ravindra Patle says

    April 13, 2016 at 7:24 AM

    C:\Program Files\Java\jdk1.8.0_66\bin>javac threadaction.java
    threadaction.java:3: error: error while writing A: A.class (Access is denied)
    class A extends Thread
    ^
    Note: threadaction.java uses or overrides a deprecated API.
    Note: Recompile with -Xlint:deprecation for details.
    1 error

    Why this error is showing ? Please help me…
    Thanks in Advance..

    Reply
  14. Utsav Oza says

    May 13, 2016 at 2:34 PM

    Where can I use Multi-Threading in my java based social networking Project.

    Reply
  15. Himani rajput says

    June 18, 2016 at 2:45 AM

    Give the different example of synchronized method of thread

    Reply
  16. lastav says

    October 2, 2016 at 10:45 AM

    its better to use lambda expressions (JDK 1.8 only)
    makes code easier to understand

    Reply
  17. Anand Pandey says

    November 7, 2016 at 3:59 PM

    Best example of Multi Threading and Multi Tasking :

    Suppose you have open two browser google chrome and Mozilla Firefox inside the chrome you have 4 tabs so you have two programs those are running simultaneously is multi processing but inside one program i.e. chrome you have 4 tabs that is multi threading.

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap