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 {
fun sendMessages(messages: List<Message>): Unit
fun stop(): Unit
}
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
sendMessagefunction; - implement the
stopfunction to shut down the executor and wait until it stops (it means blocking the thread that invokes it).
Here is an example of a testing code that should successfully work with your implementation.
val sender: AsyncMessageSender = AsyncMessageSenderImpl (3)
val messages: List<Message> = listOf(
Message ("John", "Mary", "Hello!"),
Message ("Clara", "Bruce", "How are you today?")
)
sender.sendMessages(messages)
sender.stop()
notifyAboutEnd() // it prints something after the sender successfully stops
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.