Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Use volatile keyword to prevent thread caching variables
package lecture2;
public class App{
public static void main(String[] args){
Processor prc = new Processor();
prc.start();
System.out.println("Press Return to stop");
Scanner sc = new Scanner(System.in);
sc.nextLine();
// without using the volatile keyword in the Processor class
// the prc thread may not stop printing Hello.
prc.shutdown();
}
}
package lecture2;
public class Processor extends Thread{
private volatile boolean running = true;
public void run(){
while(running){
System.out.println("Hello");
}
}
public void shutdown(){
running = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment