Notifying another class, in another thread, of a variable change?

I’m making a simple text adventure as an exercise. Well, I say simple; I’m having it run in two threads, because I want the game world to be continuously updated, whilst java’s Scanner freezes the thread to listen for user input, which isn’t what I want.

So, I have to put the scanner in another thread. Hence, I currently have:

Game.class
and
InputConsole.class

Here’s what I have in InputConsole, currently:


package textAdventure;

import java.util.Scanner;

public class InputConsole extends Thread {

	Scanner userInput = new Scanner(System.in);
	long lastInTime = System.currentTimeMillis();
	long thisInTime = lastInTime;
	String input = "";
	
	public void run() {
		while(true) {
			lastInTime = thisInTime;
			if(userInput.hasNextLine()) {	
				input = userInput.nextLine();
				thisInTime = System.currentTimeMillis();
				System.out.println(input);
			}
		}
	}
}

Now, I want to pass on the value of userinput to my Game class, with a little notification that “hey, this variable is newly changed!”. What’s a good way of doing this?

Some suboptimal solutions that occurred to me are just things like:

  • in Game.class, check the input class for a new time stamp, and if so, grab the new string
  • in Input class, change corresponding variables in Game.class

But, is there not something a bit tidier than this? Maybe something akin to action listeners?

Stick the input in a queue*, and poll the queue in your game thread.

*(obviously making sure reads & writes to the queue are properly synchronized)

http://www.javacodex.com/Concurrency/ConcurrentLinkedQueue-Example