Timer timer;
private void testRunnable(Runnable runnable, int timeInterval, Callback callback) {
timer = new Timer();
final int[] executionCount = {0};
TimerTask task = new TimerTask() {
@Override
public void run() {
runnable.run();
executionCount[0]++;
String result = "任务完成,Hello World!";
callback.onComplete(executionCount[0], result);
}
};
timer.schedule(task, 0, timeInterval);
}
@Override
protected void onDestroy() {
super.onDestroy();
timer.cancel();
}
public class CounterRunnable implements Runnable {
private AtomicInteger counter = new AtomicInteger(0);
public CounterRunnable (){
}
@Override
public void run() {
int previous = counter.getAndIncrement(); // 获取当前值并增加
// 你可以在这里处理previous值,但通常你不会从这里直接返回它
// 因为run方法没有返回值
System.out.println("Previous value: " + previous);
}
// 提供一个方法来获取当前计数
public int getCurrentCount() {
return counter.get();
}
}
//调用
CounterRunnable task = new CounterRunnable();
testRunnable(task,5000, (count, result) -> {
System.out.println("testRunnable===执行了:" + count + "次" + "===返回的结果:" + result);
int resultNew=task.getCurrentCount();
System.out.println("结果:============"+resultNew);
});
Android定时器返回结果并记录执行次数
于 2024-08-28 13:47:13 首次发布