Add listen methods to Locker to simplify event listening code

This commit is contained in:
jeffcheasey88 2023-12-03 10:12:31 +01:00
parent ec7877fe22
commit f713e3941d

View file

@ -5,6 +5,10 @@ import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
import java.util.function.Consumer;
import java.util.function.Supplier;
import dev.peerat.framework.Locker.Key;
public class Locker<V>{ public class Locker<V>{
@ -55,5 +59,51 @@ public class Locker<V>{
} }
} }
public void listen(Consumer<V> 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<Boolean> condition,Consumer<V> 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<V> action){
Thread thread = new Thread(new Runnable(){
public void run(){
listen(action);
}
});
thread.start();
return thread;
}
public Thread listenAsync(Supplier<Boolean> condition,Consumer<V> action){
Thread thread = new Thread(new Runnable(){
public void run(){
listen(condition, action);
}
});
thread.start();
return thread;
}
public static class Key{ public Key(){} } public static class Key{ public Key(){} }
} }