我试图停止 for 循环并等到该方法完成并在它调用后继续onFinish
。有人建议我使用CyclicBarrier
or syncronized wait/notify
,但它们都不起作用。
当我在没有 的情况下运行该方法时"stoppers"
,它总是到达onFinish
,调用所有 3 System.out.prints
,但是当我添加任何一个时CyclicBarrier or syncronized
,它就不会启动ticking
。这意味着它只打印第一行countDownTimer first call
然后停止并且什么也不做。
只是为了让它更短,我在stoppers
这里添加了两者来展示我是如何做到的,但我确实分别使用了它们。
我能做些什么来做到这一点"tick"
?
cyclicBarrier = new CyclicBarrier(2);
object = new Object();
for (int i = 0; i < sentenceList.size() - 1; i++) {
String currentLyricLine = sentenceList.get(i).content;
long diff = sentenceList.get(i+1).fromTime - sentenceList.get(i).fromTime;
int interval = (int) (diff / sentenceList.get(i).wordCount);
if(isFirstLine) {
startLyricCountDownTimer(diff, interval, currentLyricLine, coloredLyricsTextViewFirstLine);
isFirstLine = false;
} else {
startLyricCountDownTimer(diff, interval, currentLyricLine, coloredLyricsTextViewSecondLine);
isFirstLine = true;
}
//First tried with this
synchronized (object) {
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//Then tried with this
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}
private void startLyricCountDownTimer(final long millisInFuture, final int countDownInterval, String lyrics, final ColoredLyricsTextView coloredLyricsText){
System.out.println("countDownTimer first call" );
coloredLyricsText.setText(lyrics);
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
new CountDownTimer(millisInFuture,10) {
@Override
public void onTick(long millisUntilFinished) {
System.out.println("countDownTimer second call + " + millisUntilFinished);
//Do some stuff (irrelevant since it never gets here)
}
@Override
public void onFinish() {
System.out.println("countDownTimer last call" );
//First tried with this
synchronized (object) {
object.notify();
}
//Then tried with this
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}.start();
}
});
}
如果我理解正确,那么还提到我在 UI 线程上运行我的循环,这就是一切都停止的原因。好吧,我不想停止 UI 线程,只是等待一个countDownTimer
完成,然后开始一个新的循环。