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.



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.



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.



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.



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.

Pin It on Pinterest

Share This