Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ejercicios;
- import static es.urjc.etsii.code.concurrency.SimpleConcurrent.*;
- import static es.urjc.etsii.code.concurrency.SimpleSemaphore.*;
- import es.urjc.etsii.code.concurrency.SimpleSemaphore;
- public class ejercicio04bSemaforos {
- static final int N_CLIENTES = 3;
- static final int N_SERVIDORES = 1;
- static final int TYPE_CLIENTE = 0;
- static final int TYPE_SERVIDOR = 1;
- static final boolean DEBUG = true;
- static volatile int idCliente = 0;
- static volatile int idServidor = 0;
- static volatile int peticion = 0;
- private static SimpleSemaphore servidorDisponible = new SimpleSemaphore(0);
- private static SimpleSemaphore peticionProcesada = new SimpleSemaphore(0);
- private static SimpleSemaphore peticionEnviada = new SimpleSemaphore(0);
- public static void printI(String string, int id, int type) {
- if (DEBUG) {
- //String mensaje;
- if (type == TYPE_SERVIDOR) {
- printlnI("[SERVIDOR - "+ id +"]"+ string);
- }else if (type == TYPE_CLIENTE) {
- printlnI("[CLIENTE - "+ id +"]"+ string);
- }
- }
- }
- public static void cliente() {
- int id;
- enterMutex("idCliente");
- id = idCliente++;
- exitMutex("idCliente");
- printI("online", id, TYPE_CLIENTE);
- while (true) {
- int peticionLocal = (id * 10) + (int)(Math.random() * 9);
- servidorDisponible.acquire();
- printI("Enviando peticion "+peticionLocal, id, TYPE_CLIENTE);
- peticion = peticionLocal;
- peticionEnviada.release();
- sleepRandom(1000);
- peticionProcesada.acquire();
- servidorDisponible.release();
- printI("Peticion procesada "+peticion, id, TYPE_CLIENTE);
- }
- }
- public static void servidor() {
- int id;
- enterMutex("idServidor");
- id = idServidor++;
- exitMutex("idServidor");
- printI("online", id, TYPE_SERVIDOR);
- servidorDisponible.release();
- while (true) {
- peticionEnviada.acquire();
- peticion++;
- printI("Peticion procesada "+peticion, id, TYPE_SERVIDOR);
- peticionProcesada.release();
- //servidorDisponible.release();
- }
- }
- public static void main(String[] args) {
- createThreads(N_CLIENTES, "cliente");
- createThreads(N_SERVIDORES, "servidor");
- startThreadsAndWait();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement