How do you use volatile with a simple code example?

In Java, the `volatile` keyword is used to indicate that a variable's value will be modified by different threads. When a variable is declared as volatile, it ensures that changes made by one thread to that variable are visible to other threads. This is particularly important in multi-threaded programming to avoid memory consistency errors.

Here is a simple code example demonstrating the use of the `volatile` keyword:

public class VolatileExample { // Declare a volatile variable private static volatile boolean running = true; public static void main(String[] args) { // Start a new thread new Thread(() -> { while (running) { // Thread will continue running } System.out.println("Thread stopped."); }).start(); // Main thread sleeps for a while try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } // Update the volatile variable running = false; // This change will be visible to the other thread } }

volatile Java multi-threading memory consistency concurrency