import java.util.ArrayList;
import java.util.List;
/**
* {@link <a href=
* "https://[Log in to view URL]"
* target= "_blank">Thread, produttore-consumatore</a>}
*
* @author itammb ( Italia Massimiliano Buscati )
* @version JDK 1.15
*
*/
class Main {
public final static class ThreadProducer extends Thread {
// struttura condivisa: coda
private final List<Integer> fifo;
private int capacity = 2;
private Thread consumer;
public synchronized boolean isEmpty() {
return fifo.isEmpty();
}
public synchronized Thread getConsumer() {
return consumer;
}
public synchronized void setConsumer(Thread consumer) {
this.consumer = consumer;
}
public synchronized void putResource(int resource) throws InterruptedException {
// test: struttura condivisa piena
while (fifo.size() == capacity)
wait();
fifo.add(resource);
System.out.println("risorsa prodotta --> " + resource);
Thread.sleep(1000);
notify();
}
public synchronized int getResource() throws InterruptedException {
notify();
// test: struttura condivisa è vuota
while (fifo.isEmpty())
wait();
Thread.sleep(1000);
return fifo.remove(0);
}
public ThreadProducer() {
fifo = new ArrayList<Integer>();
}
}
public final static class ThreadConsumer extends Thread {
private ThreadProducer producer;
public synchronized ThreadProducer getProducer() {
return producer;
}
public synchronized void setProducer(ThreadProducer producer) {
this.producer = producer;
}
}
private static class UniTest {
public void simulate(ThreadProducer producer, ThreadConsumer consumer) throws InterruptedException {
configureThread(producer, consumer);
generateResource(producer);
estractorResource(consumer);
}
private void configureThread(ThreadProducer producer, ThreadConsumer consumer) {
consumer.setProducer(producer);
producer.setConsumer(consumer);
producer.start();
consumer.start();
}
private void generateResource(ThreadProducer producer) {
Thread inputCycle = new Thread(new Runnable() {
int value = 0;
@Override
public void run() {
try {
while (true)
producer.putResource(value++);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
inputCycle.start();
}
private void estractorResource(ThreadConsumer consumer) throws InterruptedException {
Thread outputCycle = new Thread(new Runnable() {
@Override
public void run() {
try {
while (true)
System.out.println("risorsa consumata --> " + consumer.getProducer().getResource());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
outputCycle.start();
outputCycle.join();
}
}
public static void main(String args[]) {
// Unit test - simulazione
try {
new UniTest().simulate(new ThreadProducer(), new ThreadConsumer());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
To embed this project on your website, copy the following code and paste it into your website's HTML: