Resumen de urgencia para el examen teórico y práctico.
run() directamente. Eso ejecuta el código en el mismo hilo.start() para crear un hilo nuevo.
Existen dos formas. Debes saber las diferencias para el test:
extends Threadimplements Runnable (RECOMENDADA)run().InterruptedException si duerme.Solo funcionan dentro de bloques synchronized.
contador++ sin control).volatile.synchronized, bloquea TODOS los métodos synchronized de ese objeto.i++).acquire(): Resta permiso.release(): Suma permiso. ¡Siempre en el finally!public synchronized void metodo() {
// SIEMPRE usar WHILE, nunca IF
while (condicionDeEspera) {
try { wait(); }
catch (InterruptedException e) {}
}
// Realizar acción
notifyAll(); // Despertar a otros
}
Semaphore sem = new Semaphore(2);
try {
sem.acquire();
// Sección crítica
} catch (Exception e) {
e.printStackTrace();
} finally {
sem.release(); // OBLIGATORIO AQUÍ
}
Selecciona las respuestas y pulsa "Corregir Examen" al final.