Write a program that simulates a simple message system. Each message has three fields: from, to and text.
The interface AsyncMessageSender describes an abstraction that can send messages and stop its work.
interface AsyncMessageSender {
public void sendMessages(Message[] messages);
public void stop();
}
The class AsyncMessageSenderImpl implements this interface and repeats each message several times (according to a variable).
Complete this class:
- it should use
ExecutorServiceto send multiple messages in parallel; - implement repeating of messages in the
sendMessagemethod; - implement the
stopmethod to shut down the executor and wait until it stops (it means it blocks a thread that invokes it).
Here is an example of a testing code that should successfully work with your implementation.
AsyncMessageSender sender = new AsyncMessageSenderImpl(3);
Message[] messages = {
new Message("John", "Mary", "Hello!"),
new Message("Clara", "Bruce", "How are you today?")
};
sender.sendMessages(messages);
sender.stop();
notifyAboutEnd(); // it prints something after the sender successfully stop
Here is the output:
(John>Mary): Hello!
(John>Mary): Hello!
(John>Mary): Hello!
(Clara>Bruce): How are you today?
(Clara>Bruce): How are you today?
(Clara>Bruce): How are you today?
Completed.
The order of the sent messages may be different, but the last line must remain the last.