Last active
August 29, 2015 13:56
-
-
Save peas/9083294 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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