// MagicThread.java
/*
 The MagicStrings class stores some magic strings
 which the client can acces one by one. The magic
 strings are a big secret, so the client can only
 get them one at a time.
 
 Each instance of MagicThread retrieves all the strings
 in order and concats them together along with the name of a
 staffer to make a little spell like this:
 "fibbity fabbity foo : Jason".
 
 The magic words have to all be there and be in the right
 order, or the spell doesn't work.
 
 Each magic thread concats its spell onto the "answer"
 static when it is done.
*/
 
 
/*
 Store magic strings -- give them
 out to the client one at a time.
*/
class MagicStrings {
	private String[] strings;
	private int index;
	
	public MagicStrings() {
		strings = new String[] {"fibbity", "fabbity", "foo"};
		index = 0;
	}
	
	/*
	 Return the next magic string, or null
	 if there are no more.
	*/
	public String nextString() {
		if (index<strings.length) {
			index++;
			return(strings[index-1]);
		}
		else {
			return(null);
		}
	}
	
	/*
	 Reset to the start so that the
	 next call to nextString() will return
	 the first magic string.
	*/
	public void reset() {
		index = 0;
	}
}


/*
 Takes a pointer to a magic object.
 Gets the strings out of it and concats
 them together.
 When done, puts the whole thing into the
 "answer" static.
*/
class MagicThread extends Thread {
	private MagicStrings magic;
	private String name;
	private static StringBuffer answer;
	
	
	public MagicThread(MagicStrings magic, String name) {
		this.magic = magic;
		this.name = name;
	}
	
	
	public void run() {
		String result = new String();
		String next;
		
		// see the magic strings in order
		magic.reset();
		while ((next = magic.nextString()) != null) {
			// concat them together
			result = result + next + " ";
		}
		answer.append(result + ": " + name + "\n");
	}
	

	/*
	 Create one magic object and three
	 threads to create a spell for each staffer.
	 The output should look like...
	 fibbity fabbity foo : Nick
	 fibbity fabbity foo : Julie
	 fibbity fabbity foo : Eric
	 
	 although the order of the rows may be mixed.
	*/
	public static void main(String[] args) {
		MagicStrings magic = new MagicStrings();
		
		
		Thread t1 = new MagicThread(magic, "Jason");
		t1.start();
		Thread t2 = new MagicThread(magic, "Saurabh");
		t2.start();
		Thread t3 = new MagicThread(magic, "Nick");
		t3.start();
		
		answer = new StringBuffer();
		
		// Wait for the three to finish
		try {
			t1.join();
			t2.join();
			t3.join();
		}
		catch (InterruptedException ignored) {}
		
		System.out.println(answer);
	}
}

