Thread Interference Error in Java


Let us see an example to understand the concept of Thread Interference error −

Example

 Live Demo

import java.io.*;
class Demo_instance{
   static int val_1 = 6;
   void increment_val(){
      for(int j=1;j<11;j++){
         val_1 = val_1 + 1;
         System.out.println("The value of i after incrementing it is "+val_1);
      }
   }
   void decrement_val(){
      for(int j=1;j<11;j++){
         val_1 = val_1 - 1;
         System.out.println("The value of i after decrementing it is "+val_1);
      }
   }
}
public class Demo{
   public static void main(String[] args){
      System.out.println("Instance of Demo_instance created");
      System.out.println("Thread instance created");
      final Demo_instance my_inst = new Demo_instance();
      Thread my_thread_1 = new Thread(){
         @Override
         public void run(){
            my_inst.increment_val();
         }
      };
      Thread my_thread_2 = new Thread(){
         @Override
         public void run(){
            my_inst.decrement_val();
         }
      };
      my_thread_1.start();
      my_thread_2.start();
   }
}

Output

Instance of Demo_instance created
Thread instance created
The value of i after incrementing it is 7
The value of i after incrementing it is 7
The value of i after decrementing it is 6
The value of i after incrementing it is 8
The value of i after decrementing it is 7
The value of i after incrementing it is 8
The value of i after incrementing it is 8
The value of i after decrementing it is 7
The value of i after incrementing it is 9
The value of i after decrementing it is 8
The value of i after decrementing it is 7
The value of i after decrementing it is 6
The value of i after decrementing it is 5
The value of i after decrementing it is 4
The value of i after decrementing it is 3
The value of i after decrementing it is 2
The value of i after incrementing it is 3
The value of i after incrementing it is 4
The value of i after incrementing it is 5
The value of i after incrementing it is 6

A class named ‘Demo_instance’ defines a static value, and a void function ‘increment_val’, that iterates over a set of numbers, and increments it and displays it on the console. Another function named ‘decrement_val’ iterates over a set of numbers and decrements every time and displays the output on the console.

A class named Demo contains the main function that creates an instance of the class, and creates a new thread. This thread is overridden, and the run function is called on this object instance. Same thing is done for the second thread too. Both these threads are then called with the ‘start’ function.

Updated on: 14-Jul-2020

118 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements