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"); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Thread stopped"); } public void stopThread() { this.keepRunning = false; } public static void main(String[] args) throws Exception{ Main v = new Main(); v.start(); Thread.sleep(3000); System.out.println("Going to set the stop flag to true"); v.stopThread(); } }
The code above generates the following result.