简体   繁体   中英

sending and receiving events in Java threads

I'm used to C++/Qt's concept of signals (emit/listen) and now I'm doing a project in Java which requires some sort of data sending/receiving mechanism.

My needs are:

  • Emit an event (with some data) and let all threads listen/catch it.
  • Obviously, given the previous requirement, being able to listen/catch signals with attached data.

Is this possible in Java, and how? (I'll appreciate a small compilable example/link)

Java by default doesn't have a simple event handling mechanism such as .Net's events or Qt's Signals and Slots. It does have the notion of Listeners in various java GUI frameworks but I don't think that's what you're looking for.

You should consider a pub-sub library like Google Guava's EventBus framework .

If you don't want to use a third party lib then I suggest you start looking into using one of the sub-classes of BlockingQueue . See the FileCrawler example from page 62 of Java Concurrency in Practice to see how to use a BlockingQueue to send events/data to worker threads.

If you're looking for a more complicated solution for message/event notifications across the process boundary or the local machine boundary then you may want to look into:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM