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

举报
炒香菇的书呆子 发表于 2022/05/24 23:53:49 2022/05/24
【摘要】 问题描述我正在使用应用程序逻辑线程和数据库访问线程创建Java应用程序。它们都在应用程序的整个生命周期内持续存在,并且两者都需要同时运行(一个与服务器通信,一个与用户通信;当应用程序完全启动时,我需要这两个可以工作)。I’m making a Java application with an application-logic-thread and a database-access-th...

问题描述

我正在使用应用程序逻辑线程和数据库访问线程创建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
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。