01 noiembrie 2010

Problema producator-consumator

Fie un vector numit buffer la care in permanenta au acces 2 entitati: un producator, care adauga elemente ori de cate ori bufferul permite acest lucru (nu se depaseste capacitatea), si un consumator care extrage elemente ori de cate ori este posibil (pana cand se ajunge la vectorul vid). In Java, simularea poate arata in felul urmator:

// clasa care creeaza cele 2 thread-uri si le porneste

import java.util.*;

class ProdCons {


public static void main (String args[]) {

Vector buffer;
int nmax;
nmax = 10;
buffer = new Vector(nmax);
for(int i=0; i<=nmax-1; i++)
buffer.addElement(i);

Prod prod = new Prod(buffer, nmax);
Cons cons = new Cons(buffer);

cons.start();
prod.start();
}

// producatorul

import java.util.*;

public class Prod extends Thread {

Vector buffer;
int cap;
int i;

public Prod (Vector buffer, int cap) {
this.cap = cap;
this.buffer = buffer;
i = 11;
}

public void run() {
while (true) {
try {
if (buffer.size()<=cap-1) {
System.out.println("Produc "+i);
buffer.addElement(i);
i++;
synchronized (buffer) {
buffer.notify(); //wakes up the first thread that called wait( ) on the same object.
}
}
synchronized (buffer) {
buffer.wait(); // tells the calling thread to give up the monitor and go to sleep until some other
//thread enters the same monitor and calls notify( ).
}
sleep(4);
}
catch (Exception e) {};
}
}

}

}

// consumatorul

import java.util.*;

public class Cons extends Thread {

Vector buffer;

public Cons (Vector buffer) {
this.buffer = buffer;
}

public void run() {
while(true) {
try {
if(buffer.size()>=1) {
System.out.println("Consum "+buffer.firstElement());
buffer.remove(buffer.firstElement());
System.out.println("buffer.size in Cons="+buffer.size());
synchronized (buffer) {
buffer.notify();
}
}
synchronized (buffer) {
buffer.wait();
}
sleep(10);
}
catch(Exception e) {};
}
}

}

Un alt exemplu mai puteti gasi AICI .

Niciun comentariu: