This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Hello. I would like to know if it's possible to have two (or more) independent threads in the same class working concurrently, and if so, how do I do it? In my application, I'm trying to have a thread continually sending messages, and another continually listening. Thanks in advance, Malc
Don't expect any of the following to work, I'm just making it up as I go... what you're looking for is the classic producer/consumer thing. A message box.The above class implements a threadsafe message box that will hold a single message. There may be multiple threads posting messages, and/or multiple threads receiving messages. If you want to get fancy you can decouple senders and receivers by adding a buffer list that will hold more than one message, etc. A simple sender could look likeThis sender will send a message through the mailbox every 0.5-1.5 seconds. A receiver could look likeWrite a main() that will create any number of senders and receivers, start() them, and off you go. After fixing the undoubted stupidities that crept in my code of course - Peter