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.