• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Threads in Java

*Please don't provide any Producer-Consumer code as this is homework*

I had to create a Producer-Consumer program in Java and I just had a question regarding threads in Java in general.

I wrote my code using a Producer/Consumer that extended the Thread class which then called Synchronized methods. Outside of one specification (The main thread needs to wait for the Consumer thread to finish) the code is completely working. But I am also told that we must use our system's timer facilities to implement the producer.

We received next to no instruction on multi-threading so I had to teach it to myself. Therefore, correct me if I am wrong - From what I understand the approach I used in Java is a Timer based approach as I use wait() and notify().

Thanks for any explanation,
-Kevin
 
It sounds like the producer puts some data in your FIFO queue at some interval, hence the use of the timer.

In your consumer, you would check to see if your queue has any data. If so, you process it. If not, you call wait() which suspends your thread and puts it into the suspend queue.

In your producer, when you put data into your FIFO queue, you should call notify() or notifyAll() to wake up any potentially sleeping consumer threads.
 
It sounds like the producer puts some data in your FIFO queue at some interval, hence the use of the timer.

In your consumer, you would check to see if your queue has any data. If so, you process it. If not, you call wait() which suspends your thread and puts it into the suspend queue.

In your producer, when you put data into your FIFO queue, you should call notify() or notifyAll() to wake up any potentially sleeping consumer threads.

Awesome I changed it last night before submitting, but I can go ahead and explain what I did.

Since the project wanted a timer, I had my Producer() class extend the TimerTask. From the main method, I executed the schedule() method at a regular interval and canceled after x iterations.

Additionally, I changed my Consumer thread from extending Thread to implementing runnable. I then spawned a new thread for that and used a join() in the main method to force the main() to wait for the threads to complete before continuing.

It was actually very interesting to see 3 different ways to implement multi-threading 🙂. Granted I only need to figure out 2 of them, but I certainly can't complain learning about the Thread interface 🙂

-Kevin
 
Back
Top