是的,Android中的CountDownLatch的計數器可以重置。你可以通過調用CountDownLatch的reset()方法來實現這一目的。這將把計數器的值設置為0,允許新的線程等待直到計數器達到0。請注意,reset()方法必須在沒有線程正在等待計數器減至0時調用,否則會拋出 IllegalStateException。
以下是一個簡單的示例:
import java.util.concurrent.CountDownLatch;
public class MainActivity extends AppCompatActivity {
private CountDownLatch countDownLatch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countDownLatch = new CountDownLatch(3);
// 啟動三個線程,它們將在未來的某個時間點完成
new Thread(new Task(countDownLatch)).start();
new Thread(new Task(countDownLatch)).start();
new Thread(new Task(countDownLatch)).start();
}
private class Task implements Runnable {
private CountDownLatch countDownLatch;
public Task(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
try {
// 模擬耗時操作
Thread.sleep(1000);
System.out.println("Task completed.");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 任務完成后,計數器減1
countDownLatch.countDown();
}
}
}
// 重置計數器的方法
public void resetCountDownLatch() {
countDownLatch.reset();
}
}
在這個示例中,我們創建了一個CountDownLatch實例,并啟動了三個線程。當所有線程完成任務后,計數器將變為0。如果你想在某個時間點重置計數器并允許新的線程等待,你可以調用resetCountDownLatch()方法。