Skip to content

Instantly share code, notes, and snippets.

@kouzouigh
Forked from samrocketman/threading.groovy
Created September 4, 2020 07:35
Show Gist options
  • Save kouzouigh/2360f6de28c2d48e02ed550f261eecd5 to your computer and use it in GitHub Desktop.
Save kouzouigh/2360f6de28c2d48e02ed550f261eecd5 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment