java如何让线程等待,如何让Java线程等待另一个线程的输出?

博客探讨了在Java应用中实现一个应用逻辑线程和数据库访问线程并确保它们同步运行的问题。作者指出在启动时,应用线程需要等待数据库线程准备就绪,目前通过轮询检测`isReady()`方法。建议使用对象锁和`wait() notifyAll()`进行线程间通信,避免空循环消耗CPU资源,并推荐学习Java并发编程的相关教程和资料以深入理解并发概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

解决方案

I would really recommend that you go through a tutorial like Sun's Java Concurrency before you commence in the magical world of multithreading.

There are also a number of good books out (google for "Concurrent Programming in Java", "Java Concurrency in Practice".

To get to your answer:

In your code that must wait for the dbThread, you must have something like this:

//do some work

synchronized(objectYouNeedToLockOn){

while (!dbThread.isReady()){

objectYouNeedToLockOn.wait();

}

}

//continue with work after dbThread is ready

In your dbThread's method, you would need to do something like this:

//do db work

synchronized(objectYouNeedToLockOn){

//set ready flag to true (so isReady returns true)

ready = true;

objectYouNeedToLockOn.notifyAll();

}

//end thread run method here

The objectYouNeedToLockOn I'm using in these examples is preferably the object that you need to manipulate concurrently from each thread, or you could create a separate Object for that purpose (I would not recommend making the methods themselves synchronized):

private final Object lock = new Object();

//now use lock in your synchronized blocks

To further your understanding:

There are other (sometimes better) ways to do the above, e.g. with CountdownLatches, etc. Since Java 5 there are a lot of nifty concurrency classes in the java.util.concurrent package and sub-packages. You really need to find material online to get to know concurrency, or get a good book.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值