Skip to content

Instantly share code, notes, and snippets.

@samrocketman
Created November 1, 2015 21:17
Show Gist options
  • Save samrocketman/3b0257f2f00bf821c789 to your computer and use it in GitHub Desktop.
Save samrocketman/3b0257f2f00bf821c789 to your computer and use it in GitHub Desktop.
//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
@ppazos
Copy link

ppazos commented Oct 30, 2017

groovier way of joining

threads*.join()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment