Groovy threads
Note: I think I’ll re-write this post, it’s a little confusing, but I’m in a rush.
I was just mucking about with threading in Groovy, it really is very simple. You pass Thread.start() a Closure. You could do something as simple as this:
Thread.start {
//# do expensive operation
}Here’s the sample code I ended up with. There are a few semi-advanced Groovy concepts here.
ReentrantLock.metaClass.withLock allows us to give all ReentrantLock instances a new method called withLock. All this does is wrap a closure (which is called by it() in the middle) with the lock.
We then define a closure called worker, that prints out some spacing depending on which thread is working (the thread number is passed in as a parameter), and some dots, and the relative time (from when we started the program).
After this definition, we actually start 5 threads off, and print “ROCK!”. The curry method is very interesting, if you don’t know what it means, you should read more about currying.
The output of the code is below the sample code.
import java.util.concurrent.locks.ReentrantLock
def startTime = System.currentTimeMillis()
ReentrantLock.metaClass.withLock = {
lock()
try {
it()
}
finally {
unlock()
}
}
def lock = new ReentrantLock()
def worker = { threadNum ->
4.times { count ->
lock.withLock {
print " " * threadNum
print "." * (count + 1)
println " ${System.currentTimeMillis() - startTime}"
}
Thread.sleep(100);
}
}
5.times {
Thread.start worker.curry(it)
}
println "ROCK!"Output:
ROCK!
. 6
. 6
. 6
. 7
. 8
.. 107
.. 107
.. 108
.. 108
.. 109
... 208
... 208
... 209
... 209
... 210
.... 311
.... 311
.... 312
.... 312
.... 313
Wed, 06 Aug 2008 11:24
Tags curry, groovy, programming, threading
2 comments »
-
By farrebls almost 2 years later:
-
By billjacksy about 2 years later:
Movie Online Plus
download film online
watch movies online for free, hollywood movies, new movies, horror movies, action movies, comedy movies, drama, musical
movie online
Делаю ручную рассылку рекламы на доски бесплатных объявлений интернета в соответствующие категории и выбором срока размещения 50$ на 3 тыс.(до 15000 досок) отчет в виде базы ссылок. Атоматическая рассылка 100$ 19000 досок. Появится в Яндексе ссылок 10000-15000 Еще варианты рассылок вышлю по запросу. ася 63619104 kasd756@inbox.ru