如何让Java线程等待另一个线程的输出?
问题描述
我正在使用应用程序逻辑线程和数据库访问线程创建Java应用程序。
它们都在应用程序的整个生命周期内持续存在,并且两者都需要同时运行(一个与服务器通信,一个与用户通信;当应用程序完全启动时,我需要这两个可以工作)。
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).
但是,在启动时,我需要确保最初应用程序线程等待直到db线程准备就绪(当前通过轮询自定义方法确定dbthread.isReady()
)。
我不介意app线程阻塞,直到db线程准备就绪。
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()
看起来不像解决方案 - 数据库线程仅在应用程序关闭时退出。
Thread.join()
doesn’t look like a solution - the db thread only exits at app shutdown.
while(!dbthread.isReady()) {}
有点工作,但空循环消耗了很多处理器周期。
while (!dbthread.isReady()) {}
kind of works, but the empty loop consumes a lot of processor cycles.
还有其他想法吗?谢谢。
Any other ideas? Thanks.
推荐答案
我真的建议您阅读像。
还有很多好书(google为Java中的并发编程,实践中的Java并发。
There are also a number of good books out (google for “Concurrent Programming in Java”, “Java Concurrency in Practice”.
来到你的回答:
在必须等待dbThread
的代码中,你必须有这样的东西:
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
在dbThread
的方法中,您需要执行以下操作:
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
objectYouNeedToLockOn
我在这些示例中使用的最好是您需要从每个线程并发操作的对象,或者您可以创建一个单独的对象
为此目的(我不建议让方法本身同步):
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
- 点赞
- 收藏
- 关注作者
评论(0)