diff --git a/src/dev/peerat/framework/Locker.java b/src/dev/peerat/framework/Locker.java index b90c448..1bfa0ee 100644 --- a/src/dev/peerat/framework/Locker.java +++ b/src/dev/peerat/framework/Locker.java @@ -5,6 +5,10 @@ import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; +import java.util.function.Consumer; +import java.util.function.Supplier; + +import dev.peerat.framework.Locker.Key; public class Locker{ @@ -55,5 +59,51 @@ public class Locker{ } } + public void listen(Consumer action){ + Key key = new Key(); + init(key); + try { + while(true){ + lock(key); + V value = getValue(key); + action.accept(value); + } + }catch(Exception e){} + remove(key); + } + + public void listen(Supplier condition,Consumer action){ + Key key = new Key(); + init(key); + try { + while(condition.get()){ + lock(key); + V value = getValue(key); + action.accept(value); + } + }catch(Exception e){} + remove(key); + } + + public Thread listenAsync(Consumer action){ + Thread thread = new Thread(new Runnable(){ + public void run(){ + listen(action); + } + }); + thread.start(); + return thread; + } + + public Thread listenAsync(Supplier condition,Consumer action){ + Thread thread = new Thread(new Runnable(){ + public void run(){ + listen(condition, action); + } + }); + thread.start(); + return thread; + } + public static class Key{ public Key(){} } }