Reputation:
I have an university assignment. On which I have to write a program with three thread. The first thread generates even number. And the second thread generates odd number. The last one sum up the odd and even numbers generated by the two threads.
I am new to Java concurrency. I have heard about producer/consumer model where a single producer produces something and a consumer used it. But In the above scenario I think, there are 2 producers - odd generator and even generator and one consumer. If I approach it to solve with producer consumer model then am I right? Or is there other technique to solve this? Can anyone mention a good example/resource link for this? Thanks.
Upvotes: 0
Views: 270
Reputation: 3353
As you mentioned that this is University assignment where you have to use 3 threads than that is what you have to do.
Most likely the point of this assignment is for you to learn about interprocess communication - see wait()
and notify()
or maybe newer locking functionality available in Java 7. Though this is just a guess based on the limited information that you provided.
Upvotes: 0
Reputation: 533590
If I approach it to solve with producer consumer model then am I right?
If that is the purpose of the exercise, then that is the right approach to take.
Or is there other technique to solve this?
You could just calculate the sum. You don't need multiple threads or even a loop.
public static long sumOfValuesUpTo(int n) {
return n * (n + 1L) / 2;
}
This is much faster and simpler. Finding a better solution is not the point of the assignment, it is to practice using multiple threads I assume.
Can anyone mention a good example/resource link for this?
Upvotes: 2