• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Multithreading » What is Multithreading in Java? – Definition
Next →
← Prev

What is Multithreading in Java? – Definition

By Dinesh Thakur

The ability of the Operating system to execute several programs simultaneously is known as multitasking. In system terminology, it is is a powerful programming tool that makes it possible to achieve concurrent execution of multiple units of a program called multithreading. In multithreading,  the application (process) is divided into two or more subprograms (processes), Several such processes originating from a single task, can be simultaneously started and handled by Java, which can be implemented at the same time in parallel. The processor is doing only one thing at a time, but it switches between the processes so fast that it appears to human beings that all of them are being done simultaneously. This mechanism of treating a single task as several independent processes simultaneously is called multithreading. Each separate process is called a thread. Each thread is executed one at a time in the CPU. Multithreading enables a program to do more than one task at a time and also to synchronize these tasks.  

A thread is similar to a program that has a single flow of control. The programs so far we have seen are called single-threaded programs, i.e., it has a beginning, a body, and an end. Java builds thread support directly into the language. Multithreading support for Java includes thread creation, thread prioritizing, thread scheduling, resource locking (thread synchronization) and establishing inter-thread communication.

Java enables us to use multiple flows of control in developing programs. Each flow of control may be thought of as a separate tiny program (or module) known as the thread that runs in parallel to others. A program that contains multiple flows of control is known as a multithreaded program.

The ability of language to support multithread is referred to as concurrency. Since threads in Java are subprograms of the main application and share the same memory space, they are also known as lightweight threads or lightweight processes.

In multithreading, the same set of variables and memory space is shared by the threads. When a thread was dealing with a sub-task, say reading an input stream, has to wait for the arrival of a byte, such a thread exit the CPU and another thread, say drawing a graphic on a screen, may enter the CPU and continue its task. Thus  Java’s thread provides a mechanism to utilize the CPU time more optimally. Multithreading finds use in a variety of applications. The threading mechanism is supported by Java’s Thread class contained in java.lang package. 

We’ll be covering the following topics in this tutorial:

  • Advantages of Multithreading 
  • What is Thread?
  • Thread Creation

Advantages of Multithreading 

1. It enables the programmers to do multiple things at a time.  
2. They can divide a long program (containing operations that are conceptually concurrent) into threads and execute them in parallel.
3. Threads are extensively used in Java-enabled browsers such as HotJava.  These browsers can download a file to the local computer, display a Web page in the window, output another Web page to a printer and so on.

What is Thread?

A thread is a single sequential flow of control within a program. It differs from a process in that a process is a program executing in its own address space whereas a thread is a single stream of execution within a process.

A thread can be defined as a process in execution within a program. A thread by itself is not a complete program and cannot run on its own. It runs within a program; however each thread has a beginning, and an end, and a sequential flow of execution at a single point of time. At any given instant within the run-time of the program, only one thread will be executed by the processor.

Multithreading allows a program to be structured as a set of individual units of control that run in parallel; however, the Central Processing Unit (CPU) can only run one process at a time. The CPU time is divided into slices and a single thread will run in a given time slice. Typically, the CPU switches between multiple threads and runs so fast that it appears as if all threads are running at the same time. It is better, as a programming practice, to identify different parts of the program that can perform in parallel and implement them into independent threads.

Multithreading differs from multitasking: multitasking allows multiple tasks (which can be processes or programs) to run concurrently whereas multithreading allows multiple units within a program (threads) to run concurrently.

Unlike the processes in some operating systems (for example, Unix), the threads in Java are ‘light-weight processes’ as they have relatively low overheads and share common memory space. This facilitates an effective and inexpensive communication between threads.

Thread Creation

When a Java program begins execution, it always has atleast one thread, i.e., the main thread. In regular Java application program, this thread starts at the beginning of main () method that means that when your program creates a thread, it is in addition to the main thread of execution that created it. Java provides two ways to make your class behave like a thread.
• By extending a java .lang. Thread class and override its run () method
• By implementing the Runnable interface and implementing its run() method

Now the question arises which of the two thread creating techniques one should use. The first technique can only be used for classes that do not already extend any other class. Therefore, we stick with the second approach which is always applicable.

Before creating a class that extends the Thread class, you need to understand the java.lang.Thread class. The Thread class lets you create an object that can be run as a thread in a multithreaded Java application. It is a direct subclass of the object class, and it implements the Runnable interface. A Thread object controls a thread running under the JVM. The Thread class contains the following constructors for creating threads and methods for controlling threads.

ConstructorsPurpose
Thread ()Creates an instance of the Thread class.
Thread(String name)Creates a Thread object and assigns a specified name to the thread.
Thread(Runnable target)Creates a new Thread object that uses the run () method of the
specified target.

 

MethodPurpose
static Thread
currentThread ()
Returns the reference of the currently executing Thread object.
void final start()Causes the associated thread to start execution. The JVM calls
the run () method of this thread.
void run ()If the thread was created using separate Runnable object
then that Runnable object’s run ()method is called, otherwise
this method does nothing and returns.
String getName()
void setName(String name)
Returns the name of the thread.

Changes the name of the thread to the one specified in the
argument.

static void sleep
(long millseconds)
Cause the currently executing thread to sleep for the specified
number of milliseconds. This method throws
InterruptedException exception and must be used within
the try catch block.
static void yield()Causes the currently running thread to temporarily pause and
allow other threads to execute.
final void setPriority
(int newPriority)
Changes the priority of the thread with the value specified in
the argument.
int getpriority()Returns threads priority.
final boolean isAlive()Tests if the thread is alive.
MethodPurpose
void setDaemon
(boolean on)
Marks the thread as either a user thread or a daemon thread.
boolean isDaemon()Tests whether a thread is Daemon thread or not.
final void join()Waits for the thread to die.
void interrupt()Interrupts a thread.
void stops ()Stops the thread.

Example of Thread

class NewThreadDemo implements Runnable {

        Thread t;

        NewThreadDemo(String threadName){

              t = new Thread(this, threadName);

                  System.out.println(“New userdefined child thread created”+threadName);

                  t.start();

         }

      public void run(){

           try{

                 for(int i =1; i <=10; i++){

                    System.out.println(“Child Thread: [“+Thread.currentThread().getName()+“] “+ i);

                    Thread.sleep(500);

                 }

            }

           catch(InterruptedException e){

                System.out.println(“UseDefine Child interrupted.”);

           }

                System.out.println(“Exiting UserDeinfed child thread.”);

    }

}

class MultiThreadDemo {

   public static void main(String args[]){

        new NewThreadDemo(“Child_One”);

        new NewThreadDemo(“Child_Two”);

        new NewThreadDemo(“Child_Three”);

        new NewThreadDemo(“Child_Four”);

        try{

            for(int i =1; i <10; i++){

                 System.out.println(“Main Thread: “+ i);

                 Thread.sleep(500);

             }

         }

         catch(InterruptedException e){

               System.out.println(“Main thread interrupted.”);

         }

                System.out.println(“Main thread exiting.”);

     }

}

Output

Multithreading

You’ll also like:

  1. Java Thread | Creating Threads and Multithreading in Java
  2. Explain Thread Priorities in Multithreading
  3. Explain Inter-Thread Communication in Multithreading
  4. What is Encapsulation in Java? – Definition
  5. Multithreading in Python
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW