这是一个修改后的蜂鸣器示例,演示了如何在每个计划任务之后做出决定。我使用了一个闩锁,这样我就可以将它包装在一个测试用例中并断言发生了正确的事情(当然是为了防止测试运行器的线程停止)。我还更改了间隔(在最初的 10 毫秒延迟后,它每 10 毫秒发出一次哔声),因此可以在一秒钟内而不是一小时内复制、粘贴和执行测试。
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class BeeperTest {
class BeeperControl {
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1, (runnable) -> {
Thread thread = new Thread(runnable);
thread.setName("MyAwesomeBeeperTestThread");
thread.setDaemon(true);
return thread;
});
public void beepTheNumberOfTimesIWant(CountDownLatch latch) {
long initialDelay = 10;
long frequency = 10;
TimeUnit unit = TimeUnit.MILLISECONDS;
final int numberOfTimesToBeep = 5;
AtomicInteger numberOfTimesIveBeeped = new AtomicInteger(0);
final ScheduledFuture[] beeperHandle = new ScheduledFuture[1];
beeperHandle[0] = scheduler.scheduleAtFixedRate(() -> {
if (numberOfTimesToBeep == numberOfTimesIveBeeped.get()) {
System.out.println("Let's get this done!");
latch.countDown();
beeperHandle[0].cancel(false);
}
else {
System.out.println("beep");
numberOfTimesIveBeeped.incrementAndGet();
}
}, initialDelay, frequency, unit);
}
}
@Test
public void beepPlease() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
BeeperControl control = new BeeperControl();
control.beepTheNumberOfTimesIWant(latch);
boolean completed = latch.await(1, TimeUnit.SECONDS);
Assert.assertTrue("Beeper should be able to finish beeping" +
"within allotted await time.", completed);
}
}