You are busy spinning in the same thread, attempting to unlock over and over again, which when the calling thread does not own the lock causes your illegal monitor state exception. In this code:
if (threadnum == i){
You are comparing a static variable to the index of the thread. Because the static variable will be the same value (after all the threads are setup), you are only invoking the while loop for the one, same thread. All the others are just blocked. And because you do this:
lock.lock();
Outside of the while loop, the sole running thread only executes correctly the first time (aka when it had the lock). In all other iterations of the loop it does not have a valid lock, so when it calls:
finally{
lock.unlock();
}
You get your illegal monitor state exception.