Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package bakery;
- /**
- *
- * @author sergio
- */
- public class Bakery extends Thread{
- // id del hilo
- public int tid;
- // número de hilos a lanzar
- public static final int numThreads = 5;
- // contador común sin acceso protegido
- public static int i = 0;
- // Array de turnos con acceso protegido
- public static volatile long[] turnos = new long[numThreads];
- // Array de persmisos con acceso protegido
- public static volatile boolean[] permisos = new boolean[numThreads];
- public Bakery(int id){
- tid = id;
- }
- @Override
- public void run() {
- for(;;) {
- preProtocolo(tid); // bloquear turno
- //Sección crítica
- System.out.println("Thread_"+ tid + ": Sección crítica. Vuelta " + ++i);
- postProtocolo(tid); // desbloquear turno
- }
- }
- /*
- * Método de preProtocolo (Bloquea la sección crítica).
- */
- public void preProtocolo(int id) {
- //Pre-protocolo
- System.out.println("Thread_"+ id + ": Pre-protocolo");
- // El hilo con el índice id pide acceso a la sección crítica
- permisos[id] = true;
- // Encuentra el turno más alto e incrementa en uno el valor del turno del hilo id
- turnos[id] = findMax() + 1;
- permisos[id] = false;
- for (int j = 0; j < numThreads; j++){
- // Si el hilo j es el hilo actual, continua al siguiente hilo
- if (j == id)
- continue;
- // Espera hasta que sea el turno del hilo j
- while (permisos[j]) {}
- while (turnos[j] != 0 && (turnos[id] > turnos[j] || (turnos[id] == turnos[j] && id > j))) {}
- }
- }
- /*
- * Método de postProtocolo (Desbloquea la sección crítica).
- */
- private void postProtocolo(int id) {
- turnos[id] = 0;
- //Post-protocolo
- System.out.println("Thread_"+ id + ": Post-protocolo");
- }
- /*
- * Método para encontrar el máximo valor en el array de turnos.
- */
- private long findMax() {
- long m = turnos[0];
- for (int j = 1; j < turnos.length; j++) {
- if (turnos[j] > m)
- m = turnos[j];
- }
- return m;
- }
- public static void main(String[] args){
- Bakery[] threads = new Bakery[numThreads];
- // Inicialización de hilos
- for (int j = 0; j < threads.length; j++) {
- threads[j] = new Bakery(j);
- threads[j].start();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement