Created
December 4, 2019 08:24
-
-
Save ajaynitt/3b0e6f859faef600ccbbf9b938f5a28c to your computer and use it in GitHub Desktop.
volatile keyword example in java
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 com.ajay.volatile_example; | |
public class VolatileTest { | |
private static volatile int MY_INT = 0; | |
public static void main(String[] args) { | |
new ChangeListener().start(); | |
new ChangeMaker().start(); | |
} | |
static class ChangeListener extends Thread { | |
@Override | |
public void run() { | |
int local_value = MY_INT; | |
while ( local_value < 5){ | |
if( local_value!= MY_INT){ | |
System.out.println("Got Change for MY_INT : " + MY_INT); | |
local_value= MY_INT; | |
} | |
} | |
} | |
} | |
static class ChangeMaker extends Thread{ | |
@Override | |
public void run() { | |
int local_value = MY_INT; | |
while (MY_INT <5){ | |
System.out.println( "Incrementing MY_INT to " + (local_value+1)); | |
MY_INT = ++local_value; | |
try { | |
Thread.sleep(500); | |
} catch (InterruptedException e) { e.printStackTrace(); } | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://medium.com/p/210f87ca13e3/edit