Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Playground {
- static class Safe {
- private final int value;
- public Safe(int value) {
- this.value = value;
- }
- }
- static class IsItSafe {
- private /* volatile */ Safe safe;
- public int get(){
- return safe.value;
- }
- public void set(int value) {
- safe = new Safe(value);
- }
- }
- private static /* volatile */ IsItSafe sharedData = new IsItSafe();
- public static void main(String[] args) {
- new Thread(new Runnable() {
- @Override
- public void run() {
- int counter = 0;
- while (counter < Integer.MAX_VALUE) {
- counter++;
- sharedData.set(counter);
- }
- System.out.printf("[T1] Shared data visible here is %d\n", sharedData.get());
- }
- }).start();
- new Thread(new Runnable() {
- @Override
- public void run() {
- int locallyRead = Integer.MIN_VALUE;
- while (sharedData.get() < Integer.MAX_VALUE) {
- locallyRead = sharedData.get();
- }
- System.out.printf("[T2] Last read value here is %d\n[T2] Shared data visible here is %d\n", locallyRead, sharedData.get());
- }
- }).start();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement