在項目中,我們通常會執行一些耗時操作,有的時候是同時執行若干個,然後執行完了還要等結果。通常我們會怎麼做呢?Handler,或者runOnUIThread。但是有沒有別的選擇了呢?有的,就是CountDownLatch
先來看個例子
public class MainActivity extends Activity {
private ArrayList<Integer> result = new ArrayList<>();
private TextView mTv1;
private ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 20, 5, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTv1 = (TextView) findViewById(R.id.txt1);
testCountDownLatch();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < result.size(); ++i) {
sb.append(i + "\n");
}
mTv1.setText(sb.toString());
}
private void testCountDownLatch() {
int threadCount = 10;
final CountDownLatch latch = new CountDownLatch(threadCount);
for (int i = 0; i < threadCount; i++) {
final int index = i;
executor.execute(new Runnable() {
@Override
public void run() {
try {
//模擬耗時操作
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 理論上這裏需要加鎖
result.add(index);
latch.countDown();
}
});
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
主要看着一段代碼:
testCountDownLatch();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < result.size(); ++i) {
sb.append(i + "\n");
}
mTv1.setText(sb.toString());
這裏會把0~9都顯示在textview上。
CountDownLatch的作用就是主線程在等待所有其它的子線程完成後再往下執行。它的好處就是異步寫法換成了同步寫法
CountDownLatch源碼解析
https://www.cnblogs.com/will-shun/p/7392619.html