How to make a Java thread wait for another thread&

2019-01-01 04:40发布

I'm making a Java application with an application-logic-thread and a database-access-thread. Both of them persist for the entire lifetime of the application and both need to be running at the same time (one talks to the server, one talks to the user; when the app is fully started, I need both of them to work).

However, on startup, I need to make sure that initially the app thread waits until the db thread is ready (currently determined by polling a custom method dbthread.isReady()). I wouldn't mind if app thread blocks until the db thread was ready.

Thread.join() doesn't look like a solution - the db thread only exits at app shutdown.

while (!dbthread.isReady()) {} kind of works, but the empty loop consumes a lot of processor cycles.

Any other ideas? Thanks.

13条回答
看淡一切
2楼-- · 2019-01-01 05:31

Since

  1. join() has been ruled out
  2. you have already using CountDownLatch and
  3. Future.get() is already proposed by other experts,

You can consider other alternatives:

  1. invokeAll from ExecutorService

    invokeAll(Collection<? extends Callable<T>> tasks)
    

    Executes the given tasks, returning a list of Futures holding their status and results when all complete.

  2. ForkJoinPool or newWorkStealingPool from Executors ( since Java 8 release)

    Creates a work-stealing thread pool using all available processors as its target parallelism level.

查看更多
登录 后发表回答