Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadLocalRandom;
public class Main {
static Semaphore resource_1 = new Semaphore(1);
static Semaphore resource_2 = new Semaphore(1);
static Semaphore resource_3 = new Semaphore(1);
static class Proceso extends Thread {
char c = ' ';
Proceso(char c) {
this.c = c;
}
public void run() {
try {
int randomNbr = ThreadLocalRandom.current().nextInt(0, 50 + 1);
for (int j=0; j<10; ++j) {
System.out.println("Solicitando el R1. Por <" + c +">");
resource_1.acquire();
try {
System.out.println("Usando el R1. Por <" + c +">");
for (int i=0; i<5; ++i) {
System.out.print(c);
Thread.sleep(randomNbr);
}
System.out.println();
} finally {
System.out.println("El recurso R1 ha sido usado Por <" + c +">");
resource_1.release();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
Proceso th1 = new Proceso('C');
th1.start();
Proceso th2 = new Proceso('J');
th2.start();
Proceso th3 = new Proceso('V');
th3.start();
th1.join();
th2.join();
th3.join();
System.out.println('\n');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.