Java Avoid Concurrency Problems with Example

Java Avoid Concurrency Problems with Example


Avoid Concurrency Problems with Example In Java
If the program is written using concurrency, however, the other tasks in the program can continue to execute when one task is blocked, so the program continues to move forward. 
In fact, from a performance standpoint, it makes no sense to use concurrency on a single-processor machine unless one of the tasks might block. 
It is best to share as minimum resources/attributes between threads as possible To avoid concurrency problem
We can use the isAlive() method If attributes need to be shared, one possible solution is to use the of the thread to check whether the thread has finished running before using any resource that the thread can change, if the first thread has not released using the resources then another thread demanding for the resources must wait otherwise deadlock will occure, or unexpected results will come.
Now we will see the examples - 
Example - 
import second.*;
import java.util.*;

class Main extends Thread{

  public static int Salary = 100000;
  public static void main(String[] args) {

      Main thread = new Main();
      thread.start();
      // Wait for the thread to finish
      while(thread.isAlive()) {
          System.out.println("Waiting...");
      }
      // Update Salary and print its value
      System.out.println("Main: " + Salary);
      Salary++;
      System.out.println("Main: " + Salary);
  }


  public void run() {
      Salary++;
      }
  }

 
Output -