I wrote this for my class solution but I don't understand how it works. I thought when you use wait(), your release the lock to other waiting thread. Then the other thread notify() lets the original thread that issued wait() to resume operation. What I don't understand is in the printAlphabet() method, I have to put wait() then notify(). Then for printDigits(), I have to put notify() and then wait().
If I just use wait() in the first one, then notify() on the second one. First, printAlphabet() prints a. Then printDigits() prints 1 and will complete the entire loop. And then printAlphabet() resumes BUT then stuck after printing letter b forever. I even asked my trainer and he couldn't figure it out neither. Appreciate any help.
class Jobs {
public void printAlphabet() throws Exception {
char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
synchronized (this) {
for (int i = 0; i < alphabet.length; i++) {
System.out.print(alphabet[i] + " ");
// System.out.println("Waiting to print digit");
wait();
Thread.sleep(1000);
notify();
}
}
}
public void printDigits() throws Exception {
String[] digits = "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".split(" ");
synchronized (this) {
for (int i = 0; i < digits.length; i++) {
System.out.print(digits[i] + " ");
// System.out.println("Waiting to print alphabet");
notify();
Thread.sleep(1000);
wait();
}
}
}
}
public class Day8Problem31 {
public static void main(String[] args) throws Exception {
Jobs task = new Jobs();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
task.printAlphabet();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
task.printDigits();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t1.start();
t2.start();
}
}