Compare
if (flag) {
wait();
}
System.out.println(msg);
flag = true;
notify();
with
if (flag == 1) {
wait();
}
System.out.println(msg);
flag = 2;
notify();
In the first case, you wait
if flag == true
and then set flag = true
. In the second case, you wait
if flag == 1
and then set flag = 2
. The logic is inverted.