[2] | 1 | import java.util.Vector;
|
---|
| 2 | import java.util.concurrent.Semaphore;
|
---|
| 3 |
|
---|
| 4 | public class SemPC{
|
---|
| 5 | public static final int N = 10;
|
---|
| 6 | public static final void main(final String[] args) {
|
---|
| 7 | Vector<Object> shared = new Vector<Object>(N);
|
---|
| 8 | Semaphore mutex = new Semaphore(1);
|
---|
| 9 | Semaphore empty = new Semaphore(N);
|
---|
| 10 | Semaphore full = new Semaphore(0);
|
---|
| 11 | Producer p = new Producer(shared, mutex, empty, full);
|
---|
| 12 | Consumer c = new Consumer(shared, mutex, empty, full);
|
---|
| 13 | p.start(); c.start();
|
---|
| 14 | }
|
---|
| 15 | }
|
---|
| 16 |
|
---|
| 17 | class Agent extends Thread{
|
---|
| 18 | protected Vector<Object> buf;
|
---|
| 19 | protected Semaphore mutex;
|
---|
| 20 | protected Semaphore empty;
|
---|
| 21 | protected Semaphore full;
|
---|
| 22 | public Agent(String name, Vector<Object> b,
|
---|
| 23 | Semaphore _mutex, Semaphore _empty, Semaphore _full){
|
---|
| 24 | super(name);
|
---|
| 25 | this.buf = b;
|
---|
| 26 | this.mutex = _mutex;
|
---|
| 27 | this.full = _full;
|
---|
| 28 | this.empty = _empty;
|
---|
| 29 | }
|
---|
| 30 | }
|
---|
| 31 |
|
---|
| 32 | class Producer extends Agent{
|
---|
| 33 | public Producer(Vector<Object> b,
|
---|
| 34 | Semaphore _mutex, Semaphore _empty, Semaphore _full) {
|
---|
| 35 | super("Producer", b, _mutex, _empty, _full);
|
---|
| 36 | }
|
---|
| 37 | public void run(){
|
---|
| 38 | while (true){
|
---|
| 39 | Object o = new Object();
|
---|
| 40 | System.out.println("Ho prodotto " + o);
|
---|
| 41 | try {
|
---|
| 42 | this.empty.acquire();
|
---|
| 43 | this.mutex.acquire();
|
---|
| 44 | this.buf.add(o);
|
---|
| 45 | this.mutex.release();
|
---|
| 46 | this.full.release();
|
---|
| 47 | } catch (InterruptedException e) {
|
---|
| 48 | System.err.println(e);
|
---|
| 49 | }
|
---|
| 50 | }
|
---|
| 51 | }
|
---|
| 52 | }
|
---|
| 53 |
|
---|
| 54 | class Consumer extends Agent{
|
---|
| 55 | public Consumer(Vector<Object> b,
|
---|
| 56 | Semaphore _mutex, Semaphore _empty, Semaphore _full) {
|
---|
| 57 | super("Consumer", b, _mutex, _empty, _full); }
|
---|
| 58 | public void run(){
|
---|
| 59 | while (true){
|
---|
| 60 | try {
|
---|
| 61 | this.full.acquire();
|
---|
| 62 | this.mutex.acquire();
|
---|
| 63 | Object o = this.buf.remove(0);
|
---|
| 64 | System.out.println("Ho consumato " + o);
|
---|
| 65 | this.mutex.release();
|
---|
| 66 | this.empty.release();
|
---|
| 67 | } catch (InterruptedException e) {
|
---|
| 68 | System.out.println(e);
|
---|
| 69 | }
|
---|
| 70 | }
|
---|
| 71 | }
|
---|
| 72 | }
|
---|
| 73 |
|
---|