package com.example.sync;

public class VolatileExample {

	// declare a volatile variable
	// volatile - always read from the main copy and not local cache
	private volatile boolean running = true;
	private volatile int number = 0;

	// write
	public void stopRunning() {
		running = false;
	}

	public void increment() {
		System.out.println(Thread.currentThread().getName() + " is running...");
		for (int i = 0; i < 5; i++) {
			number++;
			System.out.println(Thread.currentThread().getName() 
					+ " incremented: " + number);
		}
	}

	public void getNumber() {
		System.out.println(Thread.currentThread().getName() + " is running...");
		for (int i = 0; i < 5; i++) {
			System.out.println("number: " + number);
		}
	}

	// read
	public void run() {
		System.out.println("Thread started, running: " + running);
		while (running) {
			// busy wait loop
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}
		}
	}

	public static void main(String[] args) {
		VolatileExample example = new VolatileExample();

		// start a new thread
		Thread t = new Thread(example::increment);
		t.start(); // when the thread started - execute the run()

		Thread t2 = new Thread(example::getNumber);
		t2.start();

		// sleep for a short period of time
		try {
//			Thread.sleep(1000);
			t.join();
			t2.join();
		} catch (InterruptedException ex) {
		}

		// stop the thread by setting the 'running' to false
		System.out.println("Stopping the thread...");
		example.stopRunning();
	}

}
