24/02/2010, 21:50
|
(Desactivado) | | Fecha de Ingreso: diciembre-2008 Ubicación: por ahi!!!
Mensajes: 113
Antigüedad: 16 años Puntos: 1 | |
Respuesta: Productor/Consumidor en Java fijate si te sirve este ejemplo.
public class WorkQueue {
private final int nThreads;
private final PoolWorker[] threads;
private final LinkedList queue;
public WorkQueue(int nThreads) {
this.nThreads = nThreads;
queue = new LinkedList();
threads = new PoolWorker[nThreads];
for (int i = 0; i < nThreads; i++) {
threads[i] = new PoolWorker();
threads[i].start();
}
}
public void execute(Runnable r) {
synchronized (queue) {
queue.addLast(r);
queue.notify();
}
}
private class PoolWorker extends Thread {
public void run() {
Runnable r;
while (true) {
synchronized (queue) {
while (queue.isEmpty()) {
try {
System.out.println("Estoy esperando!!");
queue.wait();
} catch (InterruptedException ignored) {
}
}
r = (Runnable) queue.removeFirst();
System.out.println("fue consumido: " + r);
}
// If we don't catch RuntimeException,
// the pool could leak threads
try {
r.run();
} catch (RuntimeException e) {
// You might want to log something here
}
}
}
}
}
public class Productor implements Runnable{
public void run() {
System.out.println("estoy ejecutando: " + this);
}
}
public class TestWorkQueue extends TestCase{
public void test(){
WorkQueue workQueue = new WorkQueue(3);
for(int i=0; i < 10;i++){
Runnable r = new Productor();
workQueue.execute(r );
}
}
} |