Skip to content

Instantly share code, notes, and snippets.

@froop
Created January 25, 2015 08:53
Show Gist options
  • Save froop/c5140d49a22b5a3bce9d to your computer and use it in GitHub Desktop.
Save froop/c5140d49a22b5a3bce9d to your computer and use it in GitHub Desktop.
[Java] 別スレッドからのtrigger()をポーリングして待ち非同期に処理を実行
public class TriggerPolling implements Runnable {
private final Runnable handler;
private final int interval;
private final AtomicBoolean triggered = new AtomicBoolean();
private volatile boolean shutdown = false;
/**
* @param handler trigger()されたら実行される処理
* @param interval ポーリング間隔(ミリ秒)
*/
public TriggerPolling(Runnable handler, int interval) {
this.handler = handler;
this.interval = interval;
}
/**
* 処理実行のフラグをON.
*/
public void trigger() {
triggered.set(true);
}
/**
* スレッド終了.
*/
public void shutdown() {
shutdown = true;
}
@Override
public void run() {
try {
poll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void poll() throws InterruptedException {
while (!shutdown) {
if (triggered.getAndSet(false)) {
handler.run();
} else {
Thread.sleep(interval);
}
}
}
/**
* test.
*/
public static void main(String[] args) throws InterruptedException {
TriggerPolling target = new TriggerPolling(new Runnable() {
public void run() {
System.out.print(".");
}
}, 50);
new Thread(target).start();
for (int i = 0; i < 50; i++) {
target.trigger();
Thread.sleep(i * 10);
}
target.shutdown();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment