Skip to content

Instantly share code, notes, and snippets.

@peas
Last active August 29, 2015 13:56
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 peas/9083294 to your computer and use it in GitHub Desktop.
Save peas/9083294 to your computer and use it in GitHub Desktop.
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
class EWC {
private Consumer<Object> tarefinha;
private Queue<Object> waiters = new ConcurrentLinkedQueue<>();
public void wait(Object arg) {
Object lock = new Object();
synchronized(this) {
waiters.add(lock);
}
synchronized(lock) {
try {
System.out.println("esperando " + lock);
lock.wait();
System.out.println("recebido " + lock);
} catch(InterruptedException e) {}
if(tarefinha != null) {
tarefinha.accept(arg);
}
}
}
public void pulse (Consumer<Object> callback) {
Object w;
synchronized(this) {
w = waiters.poll();
System.out.println("removendo" + w);
this.tarefinha = callback;
}
synchronized(w) {
w.notify();
System.out.println("notificado" + w);
}
}
public void pulseAll (Consumer<Object> callback) {
List<Object> waitersCopy;
synchronized(this) {
waitersCopy = new ArrayList<>(waiters);
this.tarefinha = callback;
waiters.clear();
}
for(Object w : waitersCopy) {
synchronized(w) {
w.notifyAll();
}
}
}
}
class Kumpera {
public static void main(String ... args) throws Exception {
final EWC ewc = new EWC();
new Thread(() -> ewc.wait("paulo")).start();
new Thread(() -> ewc.wait("silveira")).start();
Thread.sleep(100);
new Thread(() -> ewc.pulse(System.out::println)).start();
Thread.sleep(100);
new Thread(() -> ewc.wait("kumpera")).start();
new Thread(() -> ewc.pulseAll(System.out::println)).start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment