Jul 12 2008

Weaving Groovy Threads

Published by Kefah Issa at 11:57 am under groovy

Could writing threads be easier than this? I wonder. :)

class Storage {
	List stack = []
 
	synchronized void leftShift (value) {
		stack << value
		println "Push : $value"
		notifyAll()
	}
 
	synchronized Object pop() {
		while(stack.isEmpty()) {
			try { wait() } catch (e) {}
		}
 
		def value = stack.pop()
		println "Pop  : $value"
		return value
	}
}
 
storage = new Storage()
 
Thread.start {
	10.times {
		storage << it
		sleep 100
	}
}
 
Thread.start {
	10.times {
		sleep 200
		value = storage.pop()
	}
}

No responses yet

Comments are closed at this time.

Trackback URI |