Skip to content

Instantly share code, notes, and snippets.

@faloi
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save faloi/b486a2dc192d2c5de9b3 to your computer and use it in GitHub Desktop.
Save faloi/b486a2dc192d2c5de9b3 to your computer and use it in GitHub Desktop.
Workspace para probar conceptos de programacion concurrente de forma simple
package edu.unq.pconc;
import java.util.Random;
import java.util.concurrent.Semaphore;
public class Main {
public static void main(String[] args) {
Semaphore semC = new Semaphore(0);
Semaphore semE = new Semaphore(0);
Semaphore semR = new Semaphore(0);
Semaphore semO = new Semaphore(0);
new Runner(
() -> {
semC.acquireUninterruptibly();
print("C");
semR.release();
semE.release();
randomSleep(); //util para forzar una "interrupcion" de vez en cuando
semE.acquireUninterruptibly();
print("E");
semO.release();
},
() -> {
print("A");
semC.release();
semR.acquireUninterruptibly();
print("R");
semO.release();
semO.acquireUninterruptibly(2);
print("O");
print("\n");
}
).start();
}
private static void randomSleep() {
try {
if (new Random().nextBoolean())
Thread.sleep(20);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private static void print(String value) {
System.out.print(value);
}
}
package edu.unq.pconc;
import java.util.Arrays;
import java.util.stream.Stream;
public class Runner {
private final Stream<Thread> threads;
public Runner(Runnable... runnables) {
threads = Arrays.asList(runnables)
.stream()
.map(runnable -> new Thread() {
public void run() {
while (true) {
runnable.run();
}
}
});
}
public void start() {
threads.forEach(Thread::start);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment