Java Tutorial

Java Tutorial Java Features C++ vs Java Java History Java Hello World Java Development Kit Java Runtime Environment Java Virtual Machine Difference between JDK, JRE, and JVM Memory Areas in Java Java Operators Java Keywords Primitive Data Types Variables

Java Loops

Java Do While Loop Java While Loop Java For Loop Java Enhanced For Loop

Java Programs

Java Basic Programs Factorial Program in Java Fibonacci Series Program in Java Prime Number Program in Java Palindrome Number Program in Java Armstrong Number Program in Java Anagram Program in Java Pattern Programs in Java Calculator Program in Java Leap Year Program in Java Addition Program in Java Number Pattern Programs in Java Star Pattern Programs in Java Package Program in Java Pyramid Program in Java Sorting Program in Java String Palindrome Program in Java Even Odd Program in Java For Loop Program in Java If Else Program in Java Switch Case Program in Java GCD Program in Java LCM Program in Java Hello Program in Java Matrix Program in Java Menu Driven Program in Java Series Program in Java Client Server Program in Java Swapping Program in Java Pig Latin Program in Java Tower of Hanoi Program in Java Recursion Program in Java Matrix Multiplication Program in Java Perfect Number Program in Java Classes and Objects in Java Example Programs String Programs in Java Array Programs in Java Constructor Program in Java Inheritance Program in Java Abstract class Program in Java Interface Program in Java Encapsulation Program in Java Polymorphism Program in Java Exception Handling Program in Java Multithreading Program in Java Thread Program in Java Collection Programs in Java ArrayList Program in Java Stack Program in Java Applet Program in Java Swing Program in Java JDBC Program in Java How to run Java program in command prompt How to run Java program in Eclipse

Java Sorting

Sorting Algorithms in Java Merge Sort in Java Quick Sort in Java Bubble Sort in Java Insertion Sort in Java Selection Sort in Java Heap Sort in Java Radix Sort in Java Topological Sort in Java Bucket Sort in Java Counting Sort in Java

Java OOPs Concepts

OOPs - Object Oriented Programming Objects and Classes in Java Java Naming Conventions Constructors in Java Java this keyword Java static keyword Inheritance in Java Aggregation in Java Java super keyword Constructor Chaining and Constructor Overloading Java Polymorphism Static and Dynamic Binding in Java Java Abstraction Abstract class in Java Interface in Java Difference between Abstract class and Interface Java final keyword Packages in Java Access Modifiers in Java Java Wrapper classes Java Numbers Java Characters Java Integer Java Boolean Java Arrays Java Command Line Arguments Java strictfp Keyword Java Math

Java Strings

Java Strings Java String Methods StringBuilder in Java StringBuffer in Java Java Regular Expressions StringBuffer vs StringBuilder String vs StringBuffer String vs StringBuilder String Manipulation in Java Java String Concatenation How to Reverse a String in Java String Array in Java How to Compare Two Strings in Java How to Concatenate Two Strings in Java Why String in Immutable in Java java.lang.NumberFormatException for Input String String Pool in Java Java Generate Random String How to take String Input in Java Java String Interview Questions

Java Exceptions

Exception Handling in Java Java try catch Java throw Java throws Difference between throw and throws Java finally Java Custom Exception Java Exception Propagation

Garbage Collection

Automatic Resource Management in Java Java Garbage Collection Java finalize() Java gc() Difference between final, finally and finalize

Multithreading

Multithreading in Java Process and Thread in Java Basic Terms in Multithreading Java Thread creation Thread Scheduler in Java Java Thread class DeadLock in Java

Java IO

Java IO Java Read File Java BufferedWriter Java InputStreamReader Java File Java Read File Line By Line Java FileOutputStream Jar File in Java

Serialization

Java Serialization Java transient

Networking

Java Network Programming Java Socket Programming Java URL Java URLConnection HttpURLConnection in Java Java InetAddress Java DatagramSocket and Java DatagramPacket

AWT

Java AWT

Swing

Swing in Java

Java Collections

Collections in Java Java List Interface ArrayList in Java LinkedList in Java Vector in Java Stack in Java ArrayList vs LinkedList in Java ArrayList vs Vector in Java Java Set Interface HashSet in Java LinkedHashSet in Java TreeSet in Java Java Queue Interface PriorityQueue in Java ArrayDeque in Java Java Map Interface HashMap in Java LinkedHashMap in Java TreeMap in Java Dictionary in Java Hashtable in Java Properties in Java Collections class in Java Java Comparable Java Comparator Comparable vs Comparator in Java

Java Generics

Generics in Java

Java Annotations

Annotations in Java

Java JDBC

Java JDBC Tutorial

Java Differences

Java vs JavaScript Python vs Java Kotlin vs Java Java vs C++ C# vs Java Static vs Non-static in Java C vs Java int vs Integer in Java Stack vs Heap in Java Java Array vs ArrayList

How to

How to run Java program How to set path in Java How to check the Java version in cmd How to install Java in Windows 10 How to run Java program in cmd How to call a method in Java How to sort an array in Java How to iterate HashMap in Java How to write Java program How to create an array in Java How to create a package in Java How to generate random numbers in Java How to input String in Java How to create thread in Java How to find length of String in Java How to sort a string in Java How to use scanner in Java How to achieve multiple inheritance in Java How to run Java program in Eclipse How to call a function in Java How to create array of objects in Java How to create custom exception in Java How to achieve abstraction in Java How to call static method in Java

Java 8 Features

Java 8 Features Lambda Expressions in Java Functional Interface in Java Streams in Java Java Base64 Encoding and Decoding Parallel Arrays Sort in Java

Java 9 Features

Java 9 Tutorial Java 9 Try With Resources Java 9 Interface Private Method

Java Servlet Tutorial

Java Servlets Tutorial

Java JSP Tutorial

Java JSP Tutorial

Hibernate Tutorial

Hibernate Tutorial

Spring Tutorial

Spring Tutorial

Spring MVC Tutorial

Spring MVC Tutorial

Jenkins Tutorial

Jenkins Tutorial

Java Math Methods

Math.abs() Math.acos() Math.addExact() Math.asin() Math.atan () Math.atan2() Math.cbrt() Math.ceil() Math.copysign() Math.cos() Math.cosh() Math.decrementExact() Math.exp() Math.expm1() Math.floor() Math.floorDiv() Math.floorMod() Math.getExponent() Math.hypot() Math.IEEEremainder() Math.incrementExact() Math.log() Math.log10() Math.log1p() Math.max() Math.min() Math.multiplyExact() Math.multiplyFull() Math.negateExact() Math.nextAfter() Math.nextDown() Math.nextUp() Math.pow() Math.random() Math.rint() Math.round() Math.scalb() Math.signum() Math.sin() Math.sinh() Math.sqrt() Math.subtractExact() Math.tan() Math.tanh() Math.toDegrees() Math.toIntExact() Math.toRadians() Math.ulp()

Java String Methods

toCharArray() copyValueOf() endsWith() equals() equalsIgnoreCase() format() getBytes() getChars() hashCode() indexOf() intern() isEmpty() join() lastIndexOf() length() replace() replaceAll() replaceFirst() split() startsWith() subSequence() substring() toLowerCase() toUpperCase() trim() valueOf()

Java Conversion

Java Convert String to int Java Convert int to String Java Convert String to long Java Convert long to String Java Convert String to float Java Convert float to String Java Convert String to double Java Convert double to String Java Convert String to Date Java Convert Date to String Java Convert String to Object Java Convert Object to String Java Convert String to char Java Convert char to String Java Convert int to long Java Convert long to int

Misc

Functional Interfaces in Java Singleton class in Java Awesome explanation of Strings in Java Object class in Java Static class in Java All the important string methods in Java String Handling Method in Java What are Array strings in Java Advantages and Disadvantages of Strings in Java Big Decimal class in Java Class definition in Java Char and String differences in Java Difference between String, StringBuffer and StringBuilder in java Replace character in string Java String Coding Interview Questions in Java What is String in Java? String isnullorempty in Java String Matches in Java Trim Method in String Java Bean class in Java Libraries in Java Arithmetic Operations on String in Java Convert Char array to string in java Check whether Java is installed or not How to calculate time difference in Java How to stop execution after a certain time in Java Jagged Array in Java Java ArraylistRemove() Time Complexity Java Swing Time Picker Zigzag Array in Java

Basic Terms in Multithreading

To understand the terms of multithreading, we must have knowledge about concurrency, processes, and threads.

Concurrency

The concurrency stands for performing multiple tasks at the same time. In the process communication, the operating system permits the process to communicate with each other. Process communication indicates that some event has occurred or data is being transferred from one process to another. There are generally two models for concurrent programming Process Communication. They are as follows:

  • Shared memory model
  • Message passing model

Shared memory Model: The concurrent modules interact with each other by reading and writing shared objects in shared memory.

Basic Terms in Multithreading

In the diagram, the shared memory can be accessed by Process1 and Process2

The shared memory is the memory that can be accessed by multiple processes simultaneously. The model is made in a way so that the processes can communicate with each other. Mostly, Windows operating systems use shared memory. Memory communication is faster on the shared memory model than the message-passing model on the same machine. It is necessary to ensure that processes using shared memory space are not allowed to write to the same memory location. The shared memory model may create problems such as synchronization and memory protection that need to be addressed.                    

Message passing Model: In this model, the concurrent modules interact with each other by sending messages through a communication channel. Modules send messages and are queued to handle incoming messages.

Basic Terms in Multithreading2

In the above diagram, both the processes process1 and process2 can access the message queue and retrieve data.

The messages are stored in the message queue until their recipient retrieves the messages. For inter-process communication, the operating system uses the message queue to communicate between the processes. Comparatively, the shared memory model is much easier to use and implement than the message-passing model.

Because the connection setup takes time, the message passing model has slower communication than the shared memory model.

Processes and Threads in the concurrency models:

Shared-memory and message-passing models are about how concurrent modules communicate with each other. Processes and threads are the two different techniques used in the concurrent modules.

Process: A process is a running program that takes place in memory. It takes a new memory that cannot be shared. The process is not able to access the memory or objects of any other process. By default, the process is ready for message- passing model as the process communicates with each other via message-passing.

Thread:  Many threads in the process run the same program and share the same memory. Because all the threads share the memory in the process so we can say Threads are automatically ready for the shared memory model.

Important terms of Multithreading:

Some essential terms that are used for multithreading are as follows:

  • Main thread
  • Daemon Thread
  • Start method
  • Run method

Java provides built-in support for multithreaded programming. It contains two or more parts that can be run concurrently. Each part of the program is called a thread, and it defines a separate path of execution.

JVM creates two types of default Threads by calling start() method automatically. First is the Main Thread, and the second is Daemon Threads.

Flow Diagram:

Basic Terms in Multithreading3

The Main Thread

Whenever we start a Java program, there is a thread that begins running immediately. This thread is the main thread of our program, which is executed at the beginning of the program.

Some points about the main thread:

  • All the child threads will be created from the main thread.
  • The main thread must be finished its execution in the last because it performs various shutdown actions.
  • For each program, the Main thread is created by JVM (Java Virtual machine). The Main thread first identifies the existence of the main() method. Then the rest of the threads are executed, which is declared in the main() method.

When our program is started, the main thread is created automatically. We can obtain a reference of the main thread by calling the method currentThread(), which is a public static member of the Thread. We can control it just like any other thread once we have a reference to the main thread.

Example:

public class ThreadDemo {
 public static void main(String args[]) {
 Thread t = Thread.currentThread();
 System.out.println("Current thread: " + t);
 // change the name of the thread 
 t.setName("My Thread");
 System.out.println("After name change: " + t);
 try {
 for(int n = 5; n > 0; n--) {
 System.out.println(n); 
 Thread.sleep(1000);
 }
 } catch (InterruptedException e) {
 System.out.println("Main thread interrupted");
 } 
 }
 } 

Output:

Basic Terms in Multithreading4

The Daemon Thread:

This thread is generally run for the background tasks such as garbage collection, checking spelling grammar, etc.

The points about Daemon thread:

  • JVM does not care whether Daemon thread is running or not; if the tasks of all the user threads are finished, it will exit from the program.
  • Whenever all user threads finish their execution, JVM terminates itself.
  • It is a low priority thread.
  • By default, any thread always is the non-daemon thread.
  • It is also known as the secondary thread.

Example:

public class ThreadDemo extends Thread {
 public ThreadDemo(String name)
 {
 super(name);
 }
 public void run() 
 {
 //checking whether the thread is Daemon or not.
 if(Thread.currentThread().isDaemon())
 {
 System.out.println(getName()+ "is Daemon thread"); 
 }
 else
 {
 System.out.println(getName()+"is user thread");    
 }
 } 
 public static void main(String args[]) {
 ThreadDemo t1=new ThreadDemo("ThreadA");
 ThreadDemo t2=new ThreadDemo("ThreadB");
 ThreadDemo t3=new ThreadDemo("ThreadC"); 
 //setting user thread t1 to Daemon.
 //it should be before starting the thread.
 t1.setDaemon(true);
 t1.start();
 t2.start(); 
 //setting user thread t3 to Daemon.
 t3.setDaemon(true);
 t3.start();
 }
 } 

Output:

Basic Terms in Multithreading5

The start() method

We can create the Thread by two ways either extending Thread class or implementing Runnable interface. In both methods, we override the run () method, but we start a thread by calling the start () method. If we call run () method directly, it will not create a new thread.

Activities that happen when a start() method is called:

  • The thread will move into the Runnable state.
  • The arguments are evaluated, and the parameters are initialized.
  • The new stack is created for new thread and associate the thread with that stack.
  • From start() ,run() method is called by JVM.

Example1:

In the below example, whenever a program calls the start() method, a new thread is created, and then the run() method is executed.

public class ThreadDemo extends Thread {
 public void run()
 {
 try
 {
 //displaying the thread that is running. 
 System.out.println("Current Thread name "+ Thread.currentThread().getName());
 System.out.println("run() method called");               
 }
 catch(Exception e)
 {
 e.printStackTrace(); 
 }
 }
 public static void main(String args[]) {
 ThreadDemo t3= new ThreadDemo(); 
 //run() is called using start()
 t3.start();
 }
 } 

Output:        

Basic Terms in Multithreading6

Explanation:

When we call start() method of our thread class instance, a new thread is created with default name Thread-0 and then run() method is called and everything inside it is executed on the newly created thread.

Example 2:

We cannot call the start() method twice. It throws a RunTimeException.

public class ThreadDemo extends Thread {
 public void run()
 {
 try
 {
 //displaying the thread that is running.
 System.out.println("Current Thread name "+ Thread.currentThread().getName()); 
 System.out.println(" run() method called");              
 }
 catch(Exception e)
 {
 e.printStackTrace(); 
 }
 }
 public static void main(String args[]) {
 ThreadDemo t3= new ThreadDemo();
 //start calls twice.
 t3.start(); 
 t3.start();
 }
 } 

Output:

Basic Terms in Multithreading7

Explanation:

As we are calling the start() method twice, it is throwing the exception as IllegalStateException .

The run method:

Features:

The run() method is the entry point of the thread execution. We can call run() method multiple times.

  • We have to pass the object of the Runnable interface implemented class in the constructor of the Thread so that the overridden run() of the Runnable class will run via the start method.
  • We can execute the overridden run() method of the Thread extended class via the start method.

Example 1:

Instead of using the start() method, the run() method can be called directly.

public class ThreadDemo extends Thread {
 public void run()
 {
 try
 {
 //displaying the thread that is running. 
 System.out.println("Current Thread name "+ Thread.currentThread().getName());
 System.out.println("run() method called");               
 }
 catch(Exception e) 
 {
 e.printStackTrace();
 }
 }
 public static void main(String args[]) { 
 ThreadDemo t3= new ThreadDemo();
 //run() is called directly without using start()
 t3.run();
 } 
 } 

Output:

Basic Terms in Multithreading8

Explanation:           

When the run() method calls of our class, no new thread is created and the run() method is executed on the current thread i.e. main thread . Hence no multithreading took place. Here the run() method is called as a normal function call.

Example 2:

We can call the run() method multiple times, as it is just a normal method calling.

public class ThreadDemo extends Thread {
 public void run()
 {
 try
 {
 //displaying the thread that is running. 
 System.out.println("Current Thread name "+ Thread.currentThread().getName());
 System.out.println(" run() method called");              
 }
 catch(Exception e) 
 {
 e.printStackTrace();
 } 
 }
 public static void main(String args[]) {
 ThreadDemo t3= new ThreadDemo();
 //run calls twice. 
 t3.run();
 t3.run();
 }
 } 

Output:

Basic Terms in Multithreading9

Explanation:

As we are calling the run() method twice, it does not raise any exception and it is executed twice as expected but on the main thread itself.

Can we call the run() method directly to start a new thread?

No, we cannot directly call run() method to start a  new thread. We need to call the start() method to create a new thread. If we call the run method directly, and it will not create a new thread, it will be in the same stack as main. There will not exist the multithreading.

What is the difference between start() and run() method?

start() run()
It creates a new thread, after that the run() method can be executed. If we directly call the run() method, no new thread is  created, and it will execute on the calling thread itself.
It cannot call more than one time. Otherwise, it will throw IllegalStateException. Multiple invocations are possible.
It is defined in the Thread class. It is defined in the Runnable interface and also in the Thread class and must be overridden in the implementing class.



ADVERTISEMENT
ADVERTISEMENT