Use volatile keyword to prevent thread caching variables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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