forked from apache/groovy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththreadring.groovy
66 lines (56 loc) · 1.44 KB
/
threadring.groovy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
* The Computer Language Benchmarks Game
* http://shootout.alioth.debian.org/
*
* contributed by Klaus Friedel
* converted to Groovy by Danno Ferrin
*/
import java.util.concurrent.locks.LockSupport
class MessageThread extends Thread {
MessageThread nextThread
volatile Integer message
MessageThread(MessageThread nextThread, int name) {
super(name as String)
this.nextThread = nextThread
}
void run() {
while (true) nextThread.enqueue(dequeue())
}
void enqueue(Integer hopsRemaining) {
if (hopsRemaining == 0) {
println(getName())
System.exit(0)
}
// as only one message populates the ring, it's impossible
// that queue is not empty
message = hopsRemaining - 1
LockSupport.unpark(this) // work waiting...
}
private Integer dequeue() {
while (message == null) {
LockSupport.park()
}
Integer msg = message
message = null
return msg
}
}
int THREAD_COUNT = 503
int hopCount = args[0] as Integer
MessageThread first
MessageThread last
(THREAD_COUNT..1).each { i ->
first = new MessageThread(first, i)
if (i == THREAD_COUNT) last = first
}
// close the ring
last.nextThread = first
// start all threads
MessageThread t = first
THREAD_COUNT.times {
t.start()
t = t.nextThread
}
// inject message
first.enqueue(hopCount)
first.join() // wait for System.exit