Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Using java.util.concurrent.Exchanger

...

An example using Exchanger. We have two threads - one keeping evens and exchanging odd values with the other thread. Meanwhile the other thread is working in reverse fashion; keeping the odds and exchanging the evens. The algorithm here is dumb in that it relies on the same number of swaps for each side - which is fine for this example but would need to be altered for more general input values.

Code Block
def x = new java.util.concurrent.Exchanger()
def (first, second) = [1..20, second=21..40], def (evens, odds)
= [[], []]
def t1 = Thread.start{ odds = first.collect{ it % 2 != 0 ? it : x.exchange(it) } }
def t2 = Thread.start{ evens = second.collect{ it % 2 == 0 ? it : x.exchange(it) } }
[t1, t2]*.join()
println "evens: $evens"
println "odds: $odds"

...