• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Java CyclicBarrier

 
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi, I would like to understand why this program waits indefinitely while the lock is lifted by two threads.


Variable 'cb' infers to CyclicBarrier type.

`new CyclicBarrier(2, () -> System.out.println("START..."));` means 2 threads must call await() so that Cyclic Barrier is tripped and barrier action is executed.

At Line n2, await() is invoked on 'cb' by Main-Thread and it waits until one more thread would invoke await() on the same object.
 
Rancher
Posts: 5114
38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

 why this program waits indefinitely


The one thread in the program is waiting at line n2.
There needs to be another thread that calls await to release the first thread.  See the example in the API doc.
 
Saloon Keeper
Posts: 5614
214
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Indeed. And you might think that switching line 17 and line 18 would solve the problem, but since Tour is still executed on the same Thread as main(), the result is the same.

As Norm says, you can see an example in the API, but this is a tad easier, me thinks
 
Marshal
Posts: 4796
601
VSCode Eclipse IDE TypeScript Redhat MicroProfile Quarkus Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
An alternative to creating the thread yourself would be to use an ExecutorService.
reply
    Bookmark Topic Watch Topic
  • New Topic