Skip to content

Instantly share code, notes, and snippets.

@jingz8804
Created October 19, 2014 16:27
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jingz8804/f58db282d7e97a9aeebb to your computer and use it in GitHub Desktop.
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