Manejo de threads con ExecutorService y Semaphore
Anteriormente manejo de threads, era un poco complicado por control de número de hilos, threads colgados (bloqueados), recursos. Con salida de Java 5 se mejoro este asunto gracias a ExecutorService y Semaphore. En siguiente ejemplo, estamos levantando 20 hilos, con pool de 10 hilos concurrentes.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class TestSemaphore {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
final Semaphore semp = new Semaphore(10);
for (int index = 0; index < 20; index++) {
final int NO = index;
Runnable run = new Runnable() {
public void run() {
try {
semp.acquire();
System.out.println("Numero: " + NO);
Thread.sleep((long) (Math.random() * 100000));
semp.release();
} catch (InterruptedException e) {
}
}
};
exec.execute(run);
}
exec.shutdown();
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class TestSemaphore {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
final Semaphore semp = new Semaphore(10);
for (int index = 0; index < 20; index++) {
final int NO = index;
Runnable run = new Runnable() {
public void run() {
try {
semp.acquire();
System.out.println("Numero: " + NO);
Thread.sleep((long) (Math.random() * 100000));
semp.release();
} catch (InterruptedException e) {
}
}
};
exec.execute(run);
}
exec.shutdown();
}
}
0 comentarios