My program require to print backward from 10 to 1. Each number print from one thread. It uses one lock with multiple condition objects. But the program cause a dead lock when I run it. This is my program.
This class working fine
import java.util.concurrent.*;
import java.util.*;
public class Backward {
public static void main(String[] args) {
BackwardThread[] threads = new BackwardThread[10];
MonitorArray monitorArray = new MonitorArray(10);
for(int i = 0; i < 10; ++i) {
threads[i] = new BackwardThread("thread" + i, i, monitorArray);
threads[i].start();
}
}
}
This class is working fine
import java.util.concurrent.*;
import java.util.*;
public class BackwardThread extends Thread {
private int id;
private MonitorArray monitorArray;
public BackwardThread(String name, int id, MonitorArray monitorArray) {
super(name);
this.id = id;
this.monitorArray = monitorArray;
}
public void run() {
monitorArray.waitTurn(id);
System.out.println("hello world thread id = " + id);
monitorArray.signalDone(id);
}
}
It seem all thread is lock forever on and conditions[id].signal() doesn't work.
import java.util.concurrent.locks.*;
import java.util.concurrent.locks.Condition;
public class MonitorArray {
private Lock lockvar;
private Condition[] conditions;
private int turn;
public MonitorArray(int num) {
this.lockvar = new ReentrantLock();
this.conditions = new Condition[num];
turn = num;
for (int i = 0; i < num; ++i) {
conditions[i] = lockvar.newCondition();
}
// TODO: need to initialize new variable here
}
public void waitTurn(int id) {
lockvar.lock();
while (id != turn) {
try {
conditions[id].await();
} catch (Exception exception) {
exception.printStackTrace();
}
}
lockvar.unlock();
}
public void signalDone(int id) {
lockvar.lock();
// TODO: Need to modify new variable here to allow one of the threads
// blocked on the while to continue
turn--;
if (id != 0) {
conditions[id].signal();
}
lockvar.unlock();
}
}