Add listen methods to Locker to simplify event listening code
This commit is contained in:
parent
ec7877fe22
commit
f713e3941d
1 changed files with 50 additions and 0 deletions
|
@ -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(){} }
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue