/*******Q4 Source Code for CS 580*********/ /*************** Zhen Chen **************/ /*****************************************/ class Range implements Runnable { int low, high; IteratorHelper ih = new IteratorHelper(this); public Range (int low, int high) { this.low = low; this.high = high; } public boolean hasNext() { return ih.done(); } public int next() { if (this.hasNext()) return ih.get(); } run () { for (int i = low; i< high; i++) { ih.yield(i); } ih.finish(); } } class IteratorHelper { private Boolean lock = false; private Boolean NoElement = false; private Thread t; private v, v1; public IteratorHelper (Runnable r) { t = new Thread(r); //creat a new thread for runnable object r this.start(); } public void start() { t.start(); //start the iterator in the new thread } public synchronized void yield( v) { while (lock) { wait(); //wait until the element is retrieved by get() } this.v = v; lock = true; // lock the yield until the value is fetched by get() notify(); //tell the get() the element is available to retrieve } public synchronized get() { while (!lock) { wait(); //wait until the element is sent by yield(); } this.v1 = this.v; //Maybe no needed, just to be safe lock = false; // release the lock for yield() notify();//tell the yield the element is sucessfully retrieved return this.v1; } public synchronized Boolean done() { if (!NoElement) return true; else { t.join(); // Job done! The end of the thread return false; } } public synchronized void finish() { NoElement = true; //No more value to yield } }