import java.util.concurrent.Semaphore;

class IncrementDemo {
	static int x = 0;

	public static void main(String[] args) {
		Semaphore incrementLock = new Semaphore(0);
		Semaphore printLock = new Semaphore(0);

		Thread incrementer = new Thread(() -> {
			for(;;) {
				try {
					incrementLock.acquire(); //Wait to be allowed to increment
				} catch (InterruptedException e) {
				}
				x++;
				printLock.release(); //Allow the printer to print
			}
		});

		Thread printer = new Thread(() -> {
			for (;;) {
				incrementLock.release(); //Let the incrementer to its job
				try {
					printLock.acquire(); //Wait to be allowed to print
				} catch (InterruptedException e) {
				}
				System.out.println(x);
			}
		});
		
		incrementer.setDaemon(false); //Keep the program alive after main() exits
		printer.setDaemon(false);
		
		incrementer.start(); //Start both threads
		printer.start();
	}

}
