dongnao6858 2015-04-15 16:17
浏览 335

Java与Golang的WaitGroup等效

Golang has something called a WaitGroup which is sort of like in Java a CompletionService or a CountDownLatch or a Semaphore or some combination of the latter.

I'm not entirely sure how you would implement a WaitGroup in Java. I would imagine a custom CompletionService with some sort of Poison message would be the route to go (since queues can't say when they are done) but perhaps there is a better concurrent data structure/lock?

EDIT I posted a possible solution below using Semaphore that I think is more analogous than using thread.join.

  • 写回答

4条回答 默认 最新

  • dongzen5577 2015-04-16 13:54
    关注

    After looking at the golang doc and confirming that Semaphore won't break with an enormous amount of permits I think a Semaphore set to Integer.MAX_VALUE is the closest to a golang WaitGroup.

    The thread.join is probably more similar to how you would use WaitGroup with goroutines since it deals with the cleanup of the threads however an isolated WaitGroup just like a Semaphore is agnostic of what increments it.

    CountdownLatch doesn't work because you need to know a priori how many threads you want to run and you cannot increment a CountdownLatch.

    Assuming the semaphore is set to Integer.MAX_VALUE:

    wg.Add(n) == semaphore.acquire(n)

    wg.Done() == semaphore.release()

    and in your thread where you want everything to stop:

    wg.Wait() == semaphore.acquire(Integer.MAX_VALUE)

    However I'm not sure all the semantics carryover so I'm not going to mark this correct for now.

    评论

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?