Java Thread Tutorial - Java Volatile Variables

The keyword volatile can keep the values of variables in a thread's working memory in sync with their values in the main memory.

We can declare a variable volatile like so:

volatile boolean flag  = true;

We can declare only a class member variable, instance or static fields, as volatile.

We can use a volatile variable as a flag to stop a thread.


The following code demonstrates the use of a volatile variable.

public class Main extends Thread {
  private volatile boolean keepRunning = true;
  public void run() {
    System.out.println("Thread started");
    while (keepRunning) {
      try {/*  w w  w .  ja v  a 2  s .c  om*/
        System.out.println("Going to sleep");
      } catch (InterruptedException e) {
    System.out.println("Thread stopped");
  public void stopThread() {
    this.keepRunning = false;
  public static void main(String[] args) throws Exception{
    Main v = new Main();
    System.out.println("Going to set the stop flag to true");

The code above generates the following result.