From the course: Parallel and Concurrent Programming with Java 2

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Barrier: Java demo

Barrier: Java demo - Java Tutorial

From the course: Parallel and Concurrent Programming with Java 2

Start my 1-month free trial

Barrier: Java demo

- [Instructor] To show you how to implement a barrier in Java I'll build on the previous example that demonstrated a race condition by creating 10 shopper threads that either added or multiplied the number of chips to buy, depending on if the thread was named Barron or Olivia. Without a barrier in place, if I run this program, it has a race condition that'll produce different results every time I run it. So, I'll use Java's cyclic barrier to make sure all five of the Olivia threads, execute their add operation before the five Barron threads multiply the bags of chips. The cyclic barrier is included in the Java concurrent package, so I'll import that at the top of the program. Then, I'll instantiate a new CyclicBarrier object called fistBump as a static variable in the Shopper class. The constructor takes an argument for the number of threads to wait on before the barrier releases. Since this program instantiates 10 shopper threads total, five named Barron and five named Olivia, and I…

Contents