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

Thread Program in Java

Thread Program in Java

Thread program in Java is the continuation of multithreading program in Java. In this topic, we will learn about the usage of threads, race condition in multithreading, synchronization, context switching, and the join() method.

Adding Elements of an Array

The addition of elements can be done using multithreading. In multithreading, we can split a given array into two or more than two halves. For each half, one thread can be created, which does the summation. Finally, a cumulative sum of all the resultants is done to get the answer. See the following code.

FileName: AddElements.java

 // importing packages
 import java.util.*;
 //random thread class
 public class AddElements implements Runnable
 {
     // two private fields of the class AddElements
     private int []array;
     private int s; // for the starting index
     private int e; // for the ending index
     // for doing the cumulative sum of the two halves
     // of the input array
     static int cumulativeSum = 0;
     // Parameterized constructor for initializing the fields
     AddElements(int []a, int s, int e)
     {
         this.array = a;
         this.s = s;
         this.e = e;
     }
     @Override
     public void run()
     {
         // invoking the method add
         add(array, s, e);
     }
     // method for adding elements
     void add(int arr[], int start, int end)
     {
         int sum = 0;
         // iterating over elements
         for(int i = start; i < end; i++)
         {
             sum = sum + arr[i];
         }
         // doing the cumulative sum of the two halves
         AddElements.cumulativeSum = AddElements.cumulativeSum + sum;
     }
    // main method
    public static void main(String argvs[]) throws InterruptedException
    {
        // input array
        int arr[] = {56, 78, 97, 89};
        // size of the array
        int size = arr.length;
        // the first object of the class AddElements
        AddElements ae1 = new AddElements(arr, 0, size / 2);
        // the second object of the class AddElements
        AddElements ae2 = new AddElements(arr, size / 2, size);
        // creating two threads
        // the first thread does the sum of the
        // first half of the input array
        Thread th1 = new Thread(ae1);
        th1.start();
        // the second thread does the addition of the
        // second half of the input array
        Thread th2 = new Thread(ae2);
        th2.start();
        // main thread waiting for
        // the first thread to finish its task
        th1.join();
        // main thread waiting for
        // the second thread to finish its task
        th2.join();
        // printing the result
        System.out.println("Sum of the elements of the given array is: " + AddElements.cumulativeSum );
    }
 } 

Output:

Sum of the elements of the given array is: 320

Explanation: We have created two objects of the AddElements class which implements the runnable interface. For each object, a thread is created. Both threads call the method add(), and do the addition of elements of their respective parts. The static variable cumulativeSum receives the results of the work done by the two threads and does the summation of those resultants. Eventually, we are displaying the result. Note that the cumulativeSum variable has to be static to get the correct result. This is because the memory allocation of the static variables happens only once and is independent of the number of objects or threads created.

Race Condition and Ambiguity in Multithreading

In multithreading, when two or more than two threads try to access the same resource at the same time, the state of race condition is reached. Also, a multithreading program may result in ambiguous behavior. Let’s understand it with the help of an example.

FileName: MyClass.java

 // MyClass is inheriting the Thread class
 public class MyClass extends Thread
 {
 // a global counter
 static int counter = 0;
 // a method for increment the value of the counter by 1
 static void increment()
 {
     // incrementing the value counter 100000 times for each thread
     for(int i = 0; i < 100000; i++)
     {
         counter++;
     }
 }
 @Override
 public synchronized void run()
 {
 increment(); // invoking the method increment()
 // getting the name of each of the thread
 String threadName = Thread.currentThread().getName();
 // displaying the result for each of the thread.
 System.out.println("Value of the variable sum for " + threadName + " is " + counter);
 }
 // main method
 public static void main(String args[])
 {
     // creating two objects of the class MyClass1
     MyClass1 obj1 = new MyClass1();
     MyClass1 obj2 = new MyClass1();
     // creating two threads
     obj1.start();
     obj2.start();
 }
 } 

Output:

 Value of the variable sum for Thread-1 is 146837
 Value of the variable sum for Thread-0 is 103188 

Explanation: In the above code, the static variable counter is shared between the two threads. Every thread is updating the value of the variable counter. Notice, no copy of the counter variable is made as counter is the static variable. Thus, the same resource (the counter variable) is shared between more than one thread, and each thread is fighting to increment the value of the counter variable by invoking the method increment(), and it is said race condition has occurred in the program.

Also, the general intuition says, first, Thread-0 is created; hence, it should be executed first, and then Thread-1. Thus, the value of the variable counter for Thread-0 should be printed first, then for Thread-1. However, the output says the opposite. Also, every thread is executing the for-loop and incrementing the value of counter variable; therefore, the final value of the variable counter should be 100000 + 100000 = 200000. However, the output never displays 200000.

Even the output mentioned above is not static! Every time the above program is executed, a different output is generated for threads 1 and 2. In the above code, these ambiguous behaviors should be ironed out.

Critical Section Synchronization Context Switching

There is one important aspect that is ignored in the above program. The absence of synchronization in the critical section of the program. Synchronization of the critical section means only one thread is allowed to enter the critical section.

Critical Section

The code which contains the resource that is shared between two or more than two threads is called the critical section of the program. In the above code, the increment() method is the critical section. This is because it contains the static variable counter that is shared between the two threads. In the above code, both the threads can enter the critical section and increment the counter variable. This leads to ambiguous results.

Context Switching

Thread-1 may start the for-loop even when Thread-0 has not finished the execution of for-loop. This is because switching between the threads execution, also known as context switching, is the duty of the Operation System, which can not be controlled by any Java program. In context switching, the Operation System holds the execution of one thread and executes another thread. After sometimes, the execution of the running thread is stopped, and the waiting thread starts its execution. This context switching happens continuously till the threads complete their execution.

We have learnt that we can not control context switching. However, we can easily control the number of threads entering the critical section. With the help of the above control, we can remove some of the ambiguity of the above program. Observe the following code.

FileName: MyClass1.java

 // MyClass is inheriting the Thread class
 public class MyClass1 extends Thread
 {
 // a global counter
 static int counter = 0;
 // a method for increment the value of the counter by 1
 static synchronized void increment()
 {
     // incrementing the value counter 100000 times for each thread
     for(int i = 0; i < 100000; i++)
     {
         counter++;
     }
 }
 @Override
 public void run()
 {
 increment(); // invoking the method increment()
 // getting the name of each of the thread
 String threadName = Thread.currentThread().getName(); 
 // displaying the result for each of the thread.
 System.out.println("Value of the variable sum for " + threadName + " is " + counter); 
 }
 // main method
 public static void main(String args[])
 {
     // creating two objects of the class MyClass
     MyClass obj1 = new MyClass();
     MyClass obj2 = new MyClass();
     // creating two threads
     obj1.start();
     obj2.start();
 }
 } 

Output:

 Value of the variable sum for Thread-0 is 105541
 Value of the variable sum for Thread-1 is 200000 

Explanation: Using the synchronization keyword, we ensured the critical section is executed by only one thread at a time. Therefore, no matter what happens, one thread is going to finish at 200000. This is because simultaneous increment of the static variable counter is ruled out. Since we can not control the context switching, the value of the variable counter for one thread keeps on changing when the above code is executed again and again. Because of the uncontrolled context switching, it is also not clear which thread will finish its execution first.  

The Join() Method

Another approach to solve the ambiguous behavior is to use the join() method. We know that context switching is leading to the uncertain outcome when the code is executed every time. Also, controlling the context switching is impossible. However, context switching can only happen when there is more than one thread executing concurrently, and the spawning of threads can easily be controlled by the join() method. The following program illustrates the same.

FileName: MyClass2.java

 // MyClass is inheriting the Thread class
 public class MyClass2 extends Thread
 {
 // a global counter
 static int counter = 0;
 // a method for increment the value of the counter by 1
 static synchronized void increment()
 {
     // incrementing the value counter 100000 times for each thread
     for(int i = 0; i < 100000; i++)
     {
         counter++;
     }
 }
 @Override
 public void run()
 {
 increment(); // invoking the method increment()
 // getting the name of each of the thread
 String threadName = Thread.currentThread().getName(); 
 // displaying the result for each of the thread.
 System.out.println("Value of the variable sum for " + threadName + " is " + counter); 
 }
 // main method
 public static void main(String args[]) throws InterruptedException
 {
     // creating two objects of the class MyClass2
     MyClass2 obj1 = new MyClass2();
     MyClass2 obj2 = new MyClass2();
     // creating two threads
     obj1.start();
     // main thread is waiting for the first thread
     // to finish the task
     obj1.join();
     obj2.start();
 }
 } 

Output:

 Value of the variable sum for Thread-0 is 100000
 Value of the variable sum for Thread-1 is 200000 

Explanation: Observe the second last statement of the main method. obj1.join(); is the new statement introduced in the code which is responsible for the elimination of all the ambiguity. It is obvious that the main thread is spawning the two new threads, one is Thread-0 and another is Thread-1. After the spawning of Thread-0, the main thread is executing the statement obj1.join();. The join() method puts the main thread in the waiting state till the Thread-0 finishes its execution. Thus, only Thread-0 is entering the critical section. Therefore, Operating System can not do the context switching. Therefore, no matter what happens, Thread-0 comes in the output before Thread-1.

After the completion of the task by Thread-0, the main thread spawns the Thread-1. Again, this time also, context switching can not happen because only one child thread is present in the program. Therefore, the output of the above program is always consistent. Try to execute the program again and again and observe the output remains the same every time.

Note that the statement obj1.join() ensures that only a child thread is present in the system. Hence, there is no chance of race condition. Therefore, we can eliminate the keyword synchronized from the method increment(). The output still remains the same.



ADVERTISEMENT
ADVERTISEMENT