Created
January 7, 2012 11:43
-
-
Save alf239/1574533 to your computer and use it in GitHub Desktop.
An example for `volatile` from http://stackoverflow.com/questions/7851327/illustrating-volatile-is-this-code-thread-safe/7851545#7851545
This file contains hidden or 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
| public class VolatileExample implements Runnable { | |
| public static boolean flag = true; // do not try this at home | |
| public void run() { | |
| long i = 0; | |
| while (flag) { | |
| if (i++ % 10000000000L == 0) | |
| System.out.println("Waiting " + System.currentTimeMillis()); | |
| } | |
| } | |
| public static void main(String[] args) throws InterruptedException { | |
| Thread thread = new Thread(new VolatileExample()); | |
| thread.start(); | |
| Thread.sleep(10000L); | |
| flag = false; | |
| long start = System.currentTimeMillis(); | |
| System.out.println("stopping " + start); | |
| thread.join(); | |
| long end = System.currentTimeMillis(); | |
| System.out.println("stopped " + end); | |
| System.out.println("Delay: " + ((end - start) / 1000L)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment