Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

synchronized

Example

Apply the synchronized modifier to mitigate race conditions among threads.

public class Main implements Runnable {
  public static int a, b;
   
  public static void main(String[] args) {
    a = 100;
    b = 100;
 
    // Check the total amount shared between a and b before the transfers
    System.out.println("Total before: " + (a + b));
 
    // Run threads which will transfer amounts between a and b
    Thread thread1 = new Thread(new Main());
    Thread thread2 = new Thread(new Main());
    thread1.start();
    thread2.start();
 
    // Wait for the threads to finish running
    try {
      thread1.join();
      thread2.join();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
 
    // Check the total amount shared between a and b after the transfers
   
// It should be the same amount as before
    System.out.println("Total after: " + (a + b));
  }
  public void run() {
    for (int i = 0; i < 10000000; i++) {
      transfer();
    }
  }

 
public static synchronized void transfer() {
    // Choose a random amount to transfer
    int amount = (int) (5.0 * Math.random());

    // Transfer between a and b
    if (a > b) {
      a -= amount;
      b += amount;
    } else {
      a += amount;
      b -= amount;
    }
  }
}

Definition and Usage

The synchronized keyword serves as a modifier that locks a method, ensuring exclusive access by only one thread at a time. This prevents issues stemming from race conditions between threads.

In the provided example, if the synchronized keyword is removed from the transfer() method, it may allow another thread to modify the values of a and b concurrently with ongoing operations. Consequently, this could lead to changes in the total amount represented by the two variables.