Witam, potrzebuje pilnej pomocy, temat: problem producentów i konsumentów z wykorzystaniem stosu.
Coś tam sklepałem, ale nie działa tak jak powinno i proszę Was o pomoc, błędy pewnie trywialne, ale cóż.. uczę się :)
public class Stack {
private int [] tab;
private int wierzch = 0;
/***************** Konstruktor (rozmiarStosu) ****************/
public Stack(int rozmiar) {
tab = new int[rozmiar];
wierzch = 0;
}
/********************* Produkcja ************/
public synchronized void push(int E) {
if (wierzch < tab.length) {
tab[wierzch] = E;
wierzch++;
System.out.println("\nWyprodukowano element: " +tab[wierzch]);
notifyAll();
} else {
try {
System.out.println("\nMagazyn pełny, producnet czeka...\n");
Thread.currentThread().wait();
} catch (InterruptedException e) {
}
}
}
/******************** Konsumpcja **************/
public synchronized int pop() {
if (wierzch <= 0) {
try {
System.out.println("\nMagazyn pusty, konsument czeka...\n");
Thread.currentThread().wait();
} catch (InterruptedException e) {
}
}
int temp = tab[wierzch - 1];
wierzch--;
System.out.println("Skonsumowano element: " +tab[wierzch]);
return temp;
}
/******************** MAIN **********************/
public static void main(String [] args) {
Stack stos = new Stack(100);
for(int i = 0; i<20;i++) {
new Producent(stos).start();
new Konsument(stos).start();
}
}
}
import java.util.Random;
public class Producent extends Thread {
Stack stos;
public Producent(Stack stos) {
this.stos = stos;
}
@Override
public void run() {
Random r = new Random();
stos.push((r.nextInt())/100000);
}
}
public class Konsument extends Thread {
Stack stos;
public Konsument(Stack stos) {
this.stos = stos;
}
@Override
public void run() {
stos.pop();
}
}
Pozdrawiam i proszę o wyrozumiałość.