Last active
August 29, 2015 14:07
-
-
Save faloi/b486a2dc192d2c5de9b3 to your computer and use it in GitHub Desktop.
Workspace para probar conceptos de programacion concurrente de forma simple
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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