It’s the night before my Software Methodology exam, Vicki and I are hungry and decided to order food from Noodle Gourmet…and I think I am having too much fun learning how thread synchronization works in Java.

(For those of you who don’t know me: Vicki is my flatmate and partner in crime, and I detest all seafood hahaha)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
public class Conversation {

	public static void main(String[] args) {
		Round r = new Round();
		new Jenny(r);
		new Vicki(r);
	}

}

class Round {

	boolean available = false;

	public synchronized void ask(String msg) {
		while (available) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println(Thread.currentThread().getName() +
				": " + msg);
		available = true;
		notify();
	}

	public synchronized void answer(String msg) {
		while (!available) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println(Thread.currentThread().getName() +
				": " + msg);
		available = false;
		notify();
	}
}

class Jenny implements Runnable {

	Round r;
	String[] talk = { "What are you eating?" , "Ewww.",
			"I politely decline your offer. :P" };

	public Jenny(Round r) {
		this.r = r;
		new Thread(this, "Jenny").start();
	}

	@Override
	public void run() {
		for (String s : talk) {
			r.ask(s);
		}
	}

}

class Vicki implements Runnable {

	Round r;
	String[] talk = { "Fish cake." , "Would you like some? :P",
			"LOLOL." };

	public Vicki(Round r) {
		this.r = r;
		new Thread(this, "Vicki").start();
	}

	@Override
	public void run() {
		for (String s : talk) {
			r.answer(s);
		}
	}

}

When you compile and run the above code, you’ll get this little conversation:

Jenny: What are you eating?
Vicki: Fish cake.
Jenny: Ewww.
Vicki: Would you like some? :P
Jenny: I politely decline your offer. :P
Vicki: LOLOL.

Anyways, back to studying. D: