synchronization - Using Java Monitors for the first time (homework) -
here question:
a grouping of monkeys seek cross river using old rope. rope connects 2 sides of river bank , monkeys can cross river climbing rope hand-over-hand. rope old, can take @ 3 monkeys @ time. otherwise, rope breaks , monkeys fall water. additionally, if rightward monkey encounters leftward monkey on rope, ght each other , fall water. create java class monkeyking arranges grouping of monkeys cross river safely. implementation of monkeyking uses java monitor (wait(), notify(), , notifyall()) synchronize monkeys. class provides next method:
public synchronized climbrope(int direction) // monkey calls method when arrives @ river bank , wants // climb rope in specified direction (0 or 1); method blocks // monkey until allowed climb rope public synchronized leaverope() // after monkey crossing river, phone call method, // allows other monkeys climb rope.
you not need worry implementation of monkeys, synchronization should free deadlock , no monkey should prevented climbing rope unnecessarily
unfortunately don't have specific question @ moment, need help on how should getting started here, because quite lost. can see how climbrope need implement wait() , leaverope need implement notify()/notifyall(), stuck figuring out monkeyking's run() method. i'm assuming monkeyking implement runnable here, hints/tips on run() method should doing/look like?
edit: i'm working on solution no run method don't think it's needed:
public class monkeyking { int monkeysonrope=0; int currentdirection=-1; public synchronized void climbrope(int direction) { seek { if(monkeysonrope==0){ currentdirection=direction; } while((monkeysonrope>=3) || (currentdirection != direction)){ wait(); } } grab (interruptedexception e) { e.printstacktrace(); } finally{ monkeysonrope++; } } public synchronized void leaverope(){ monkeysonrope--; notify(); } }
does okay far? i'm little worried 2 threads hitting initial seek block @ same same time , potentially putting 2 monkeys on rope going opposite directions. potentially happen setup? , if so... ways avoid it?
java synchronization
No comments:
Post a Comment