In the code below I want Thread t1 to execute produce of Runnable and Thread t2 to execute consume of Runnable.
The first answer is that most likely you don't want to do this. You should have a producer class and a consumer class. If they need to share data then fine but you should separate your producer and consumer code for modularity purposes. For example, the producer and consumer code could share a BlockingQueue
that would be passed into both classes and used for them to exchange work.
As your code is currently written, each of the threads is obviously just going to call produce()
and then consume()
. I assume the code was written as an example.
If you really wanted to combine the producer and consumer code in the same class, you could pass some sort of boolean or other selector to tell the thread to either produce or consume.
For example:
public class ProducerConsumerRunnable implements Runnable {
private final Processor processor;
private final boolean consume;
public ProducerConsumerRunnable(Processor processor, boolean consume) {
this.processor = processor;
this.consume = consume;
}
public void run() {
if (consume) {
processor.consume()
} else {
processor.produce()
}
}
}
So then you would start your threads like:
Processor p = new Processor()
Thread producerThread = new Thread(new ProducerConsumerRunnable(p, false));
producerThread.start();
Thread consumerThread = new Thread(new ProducerConsumerRunnable(p, true));
consumerThread.start();
Edit:
Initial your code was calling thread.run()
when you should be calling thread.start()
. Calling run()
will just run the runnable in the foreground thread while start()
actually forks a thread in the background that then calls run.