Created
August 6, 2017 07:29
-
-
Save arunlakshman/7a7333f8871ce12a0ea1863216df24b1 to your computer and use it in GitHub Desktop.
Java Volatile Keyword
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
public class VolatileTest { | |
private static final int MAX_TASK_COUNT = 5; | |
private static volatile int tasks = 0; | |
public static void main(String[] args) { | |
new Employee().start(); | |
new Manager().start(); | |
} | |
static class Employee extends Thread { | |
@Override | |
public void run() { | |
int local_value = tasks; | |
while (local_value < MAX_TASK_COUNT) { | |
if (local_value != tasks) { | |
System.out.println("Got Change for tasks : " + tasks); | |
local_value = tasks; | |
} | |
} | |
} | |
} | |
static class Manager extends Thread { | |
@Override | |
public void run() { | |
int local_value = tasks; | |
while (tasks < MAX_TASK_COUNT) { | |
System.out.println("Incrementing tasks to " + (local_value + 1)); | |
tasks = ++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