|
||
---|---|---|
.. | ||
Exchanger.java | ||
ExchangerTester.java | ||
README.md |
README.md
Problem 4.1: Data exchange point between two threads
Implement a class Exchanger<T>
that is usable to exchange an object
of type T
between exactly two threads:
class Exchanger<T> {
// your task
T exchange(T s) {
// your task
}
}
Every thread invokes method exchange()
with the object it wants to pass to the other thread and
receives as the result of that invocation the object that the other thread has passed. Make sure that
your code works even when both threads happen to pass the same object.
Initially, your Exchanger should be usable for a single exchange only. Then, add functionality to make it usable repeatedly by the same two threads. In a third step, extend your class to make it usable by any number of threads: Each time, the "next two" threads perform an exchange among each other; note that in this scenario it may happen that a thread uses an exchanger where the previous exchange has not yet finished.
In the source code folder on the server you'll find a class ExchangerTester
that tests your
Exchanger
(only for a single exchange; you can extend it yourself so as to test a series of exchanges).
The output of that program should look as follows:
Main thread received World in exchange for Hello
2nd thread received Hello in exchange for World
2nd thread received 2337 in exchange for 2337
Main thread received 2337 in exchange for 2337