Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package Proyecto2;
- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.ReentrantLock;
- /**
- *
- * @author igor_
- */
- public class Agencia {
- ReentrantLock candado;
- Condition c1,c2;
- private int agenteA,agenteB;
- private int clientesViajes;
- public Agencia(){
- agenteA=-1;
- agenteB=-1;
- candado = new ReentrantLock();
- c1 = candado.newCondition(); // clientes de viajes
- c2 = candado.newCondition(); // clientes de entradas
- clientesViajes = 0;
- }
- public void EntraVijae(int id){
- candado.lock();
- try{
- while(agenteA != -1 && agenteB != -1){
- clientesViajes++;
- c1.await();
- clientesViajes--;
- }
- if(agenteA == -1){
- agenteA=id;
- }else{
- agenteB=id;
- }
- }catch(Exception e){
- System.out.println("Fallo den el EntraViajes: "+e.getMessage());
- }
- candado.unlock();
- }
- public void SaleViaje(int id){
- candado.lock();
- if(id==agenteA){
- agenteA=-1;
- }else{
- agenteB=-1;
- }
- if(clientesViajes>0){
- c1.notify();
- }else{
- c2.notify();
- }
- candado.unlock();
- }
- public void EntraEntradas(int id){
- candado.lock();
- try{
- while(agenteA != -1 && agenteB != -1 || (agenteB != -1 && clientesViajes != 0)){
- c2.await();
- }
- if(agenteB == -1){
- agenteB=id;
- }else{
- agenteA=id;
- }
- }catch(Exception e){
- System.out.println("Fallo den el EntraViajes: "+e.getMessage());
- }
- candado.unlock();
- }
- public void SaleEntradas(int id){
- candado.lock();
- if(id==agenteA){
- agenteA=-1;
- }else{
- agenteB=-1;
- }
- c2.signal(); // como c2 y c1 son igual de importantes para el agenteB, los ejecutamos sin comprobaciones
- c1.signal();
- candado.unlock();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement