Created
November 1, 2015 21:17
-
-
Save samrocketman/3b0257f2f00bf821c789 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//http://chrisbroadfoot.id.au/2008/08/06/groovy-threads/ | |
//http://docs.groovy-lang.org/latest/html/gapi/groovy/transform/Synchronized.html | |
//https://github.com/jenkinsci/jenkins-scripts/blob/master/scriptler/findOfflineSlaves.groovy | |
import java.util.concurrent.locks.ReentrantLock | |
ReentrantLock.metaClass.withLock = { | |
lock() | |
try { | |
it() | |
} | |
finally { | |
unlock() | |
} | |
} | |
def lock = new ReentrantLock() | |
List<Thread> threads = [] | |
List results = [] | |
threads << Thread.start { | |
sleep(1000) | |
//protect this shared data from a race condition | |
lock.withLock { | |
results << "hello" | |
} | |
println "Hello sam" | |
} | |
threads << Thread.start { | |
//protect this shared data from a race condition while modifying it | |
lock.withLock { | |
results << "hello2" | |
} | |
println "Hello sam" | |
} | |
//gate to wait for all threads | |
threads.each { | |
it.join() | |
} | |
//notice hello2 is in the results list first even though it was defined after hello in this file | |
results |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
groovier way of joining
threads*.join()