不确定它是否完全符合您的要求,但我写这篇文章是为了暂停一段时间,但让其他线程过早唤醒我。
它在BlockingQueue
内部使用 a 来做它的睡眠,因此它避免使用sleep
和wait
所有伴随它们而来的悲伤。
不确定它在 Android 下会如何运作,我不使用它,但我怀疑你现有的AlarmManager
工作会适应。
/**
* Use one of these to doze for a certain time.
*
* The dozing is fully interruptable.
*
* Another thread can stop the caller's doze with either a wakeup call or an abort call.
*
* These can be interpreted in any way you like but it is intended that a Wakeup is
* interpreted as a normal awakening and should probably be treated in exactly the
* same way as an Alarm. An Abort should probably be interpreted as a suggestion
* to abandon the process.
*/
public class Doze {
// Special alarm messages.
public enum Alarm {
// Standard timeout.
Alarm,
// Forced wake from your doze.
Wakeup,
// Abort the whole Doze process.
Abort;
}
// My queue to wait on.
private final BlockingQueue<Alarm> doze = new ArrayBlockingQueue<>(1);
// How long to wait by default.
private final long wait;
public Doze(long wait) {
this.wait = wait;
}
public Doze() {
this(0);
}
public Alarm doze() throws InterruptedException {
// Wait that long.
return doze(wait);
}
public Alarm doze(long wait) throws InterruptedException {
// Wait that long.
Alarm poll = doze.poll(wait, TimeUnit.MILLISECONDS);
// If we got nothing then it must be a normal wakeup.
return poll == null ? Alarm.Alarm : poll;
}
public void wakeup() {
// Just post a Wakeup.
doze.add(Alarm.Wakeup);
}
public void abort() {
// Signal the system to abort.
doze.add(Alarm.Abort);
}
private static long elapsed ( long start ) {
return System.currentTimeMillis() - start;
}
// Test code.
public static void main(String[] args) throws InterruptedException {
// Doze for 1 second at a time.
final Doze d = new Doze(1 * 1000);
final long start = System.currentTimeMillis();
// Start a dozing thread.
new Thread(new Runnable() {
@Override
public void run() {
try {
Alarm a = d.doze();
// Wait forever until we are aborted.
while (a != Alarm.Abort) {
System.out.println(elapsed(start) + ": Doze returned " + a);
a = d.doze();
}
System.out.println(elapsed(start) + ": Doze returned " + a);
} catch (InterruptedException ex) {
// Just exit on interrupt.
}
}
}).start();
// Wait for a few seconds.
Thread.sleep(3210);
// Wake it up.
d.wakeup();
// Wait for a few seconds.
Thread.sleep(4321);
// Abort it.
d.abort();
}
}