Home Java Docker
Home     Java

Java Topic

What is Java
History of Java
Freature of Java
Difference Between Java & C++
Java Environment Set Up
Java Hello World Program & its Internal Process
Java Hello World Program
JDK, JRE and JVM
Java Variables
Java Data Types & Unicode System
Java Operators
Java Keywords
Java Control Statements
Java if else
Java switch
Java for loop
Java While loop
Java Do While loop
Java break
Java continue
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Java Inheritance
Java Hybrid Inheritance
Aggregation(HAS-A)
Java Polymorphism
Java method overloading
Java method overriding
Java Runtime polymorphism
Java Dynamic Binding
Super keyword
Final keyword
Difference Between method overloading and method overriding
Java Abstraction
Java Interface
Abstract class vs Interface
Java Encapsulation
Java Package
Java Access Modifiers
covariant return type
Instance initializer block
Java instanceof operator
Object Cloning in Java
Wrapper classes in Java
Java Strictfp Keyword
Recursion in Java
Java Command Line Arguments
Difference between object and class
Java String
Java String Class
Java Immutable String
Java Immutable Class
String Buffer
String Builder
String Buffer vs String
String Builder vs String Buffer
String Tokenizer in Java
Java Array
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java
Java Applet
Animation in Applet
EventHandling in Applet
Display image in Applet
Displaying Graphics in Applet
Parameter in Applet
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements

Multithreading in Java

  • The act of running multiple threads concurrently in Java is known as multithreading.
    • Java's multithreading feature divides tasks into thread-sized components, enabling you to complete multiple tasks at once. Threads are like tiny sub-processes that can run concurrently. Multithreading combines both multiprocessing and multitasking to achieve efficient multitasking in Java programming.
    • Due to the shared memory space it uses, multithreading in Java is preferred over multiprocessing. This approach offers memory efficiency by eliminating the need for separate memory allocations. Additionally, the context switching between threads is faster compared to processes.
Table Of Content

  • Multithreading in Java
  • Advantages of Java Multithreading
  • Multitasking
  • What is Thread
  • Creating threads by extending the Thread class
  • Thread creation by implementing the Runnable Interface







Advantages of Java Multithreading

  • Since each thread is independent and allows for simultaneous execution of multiple operations, the user is not blocked.
  • It saves time because multiple tasks can be completed simultaneously.
  • Multithreading in Java enables the simultaneous execution of multiple independent threads. This concurrency feature ensures that exceptions encountered in one thread do not disrupt the execution of other threads.


Multitasking

  • Executing several tasks at once is known as multitasking. There are two ways to achive multitask.
    • Multitasking Based on Process (Multiprocessing)
    • Multitasking based on Threads (Multithreading)

Multitasking Based on Process (Multiprocessing)

  • Each process in Java operates with its own unique memory address, signifying its distinct memory area.
  • Processes in Java are resource-intensive, resulting in expensive communication between them.
  • The process switching in Java entails saving and loading registers, memory maps, update lists, and other operations, which contribute to a time delay.





Multitasking based on Threads (Multithreading)

  • Lightweight processes within processes are called threads.
  • The same address space is used by all threads.
  • Multithreading in Java enables concurrent execution of multiple threads within a program. Threads in Java are lightweight and have efficient communication, resulting in minimal overhead.
  • For each thread, at least one process is necessary.

What is Thread in java

In Java, a thread is a small part of a program that can be executed independently. It allows concurrent execution of multiple tasks or processes, enabling programs to perform multiple operations simultaneously. Parallelism can be achieved and system resources, like CPU cores, can be used to the fullest extent possible thanks to threads.


The Thread class, which is a component of the java.lang package, is used to represent threads in Java. By creating and managing threads, developers can execute different sections of code concurrently, leading to improved performance and responsiveness in multi-tasking scenarios.


Threads can be created by using two mechanisms

  • Extending the Thread class
  • Implementing the Runnable Interface


Creating threads by extending the Thread class


A class that extends java.lang is created. thread type. The run() method of the Thread class is overridden by this class. A thread is created inside the run() method. In order to initiate the execution of a thread, we create an object of our new class and call the start() method. Start() calls the Thread object's run() method.


class Multithreadings extends Thread {
    public void run(){
        try {
            System.out.println("Thread " + Thread.currentThread().getId()+ "running");
        }
        catch (Exception e) {
            System.out.println("Exception caught");
        }
    }
}
public class Main { // class to use user define above exception
	public static void main(String args[]){
        int th = 5; // Number of threads
        for (int i = 0; i < th; i++) {
        	Multithreadings object= new Multithreadings();
        	object.start();
        }
	}
}




Output:

Thread 17 running
Thread 14 running
Thread 18 running
Thread 15 running
Thread 16 running 


Thread creation by implementing the runnable interface


We develop a brand-new class that complies with Java.lang. run() method is overridden by the runnable interface. After that, we create a Thread object and call its start() method.


class Multithreadings implements Runnable  {
    public void run(){
        try {
            System.out.println("Thread " + Thread.currentThread().getId()+ " running");
        }
        catch (Exception e) {
            System.out.println("Exception caught");
        }
    }
}
public class Main { // class to use user define above exception
	public static void main(String args[]){
        int th = 5; // Number of threads
        for (int i = 0; i < th; i++) {
        	Thread  thread= new Thread(new Multithreadings());
        	thread.start();
        }
   }
}




Output:

Thread 14 running
Thread 18 running
Thread 17 running
Thread 16 running
Thread 15 running 

What we learn in multithreading

  • Java Multithreading

  • Lifecycle and States of a Thread in Java
  • How to create a thread in Java
  • Thread Scheduler in Java
  • Sleeping a thread in Java
  • Calling run() method
  • Joining a thread in Java
  • Naming a thread in Java
  • Thread Priority
  • Daemon Thread
  • Thread Pool
  • Thread Group
  • Shutdown hook
  • Multitasking vs Multithreading
  • Garbage Collection
  • RunTime Class



lifecycle & states of a thread in java Next »
« Perv Next »


Post your comment





Read Next Topic
Java Tutorial - Topic
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class

Read Other Java Chapter
Java Topic
Java Basic Tutorial
Java Control Statements
Java Classes & Object
Java Inheritance
Java Polymorphism
Java Abstraction
Java Encapsulation
Java OOPs Miscellaneous
Java Array
Java String
Java Exception Handling
Java Multithreading
Java Synchronization
Java Applet
Java 8 Features
Java 9 Features
Java Collection
Java Mcq
Java Interview Question
Tools
  

Useful Links

  • Home
  • Blog
  • About us
  • Contact Us
  • Privacy policy

Contact Us

Police Colony
Patna, Bihar
India

Email:

About DockerTpoint


India's largest site for Programming Tutorial as well as BANK, SSC, RAILWAY exam
and Campus placement preparation.