How to develop producer consumer like applications in Java?
I have to develop an application similar to the producer - consumer problem in Java
But I don't know much about Java. I have a few questions
Producers and consumers are different threads, and they all need to access the same buffer If they are all different classes (extending thread classes or implementing runnable interfaces), how can I code them to use exactly the same buffer (this hypothetical buffer is an array of objects)?
I also want to know some suggestions about the overall architecture and how to implement them I need to encode them so that two threads will not use the same buffer location at the same time, and two generator threads will not insert exactly the same value at the same time. The producer cannot insert a new item into a new item. The new item has filled the buffer. When the buffer is empty, no consumer should consume it
In this example, several consumers and several producers must work at the same time
I looked up some examples in Java, but they were completely different from what I needed
Solution
You can pass the same array or list instance to consumers and producers by passing their constructors
Array a = new Array(); Consumer c = new Consumer(a); Producer p = new Producer(a);
For the second question, you want to know (Google it!) For synchronization in Java You can pass in the same private object lock1 = new object(); Both consumers and producers can use it as a shared lock
http://download.oracle.com/javase/tutorial/essential/concurrency/locksync.html
Whenever a consumer or producer accesses a shared array, they need to obtain a lock first Other conditional requirements, such as "do not insert elements when the array is full" or "do not consume elements when the array is empty" can be implemented in the synchronization block
public void add(Object someObject){ synchronized (lock1) { if(a.size()>limit) { System.out.println("Array is full"); } else { a.add(someObject) } } }