在项目中,我们通常会执行一些耗时操作,有的时候是同时执行若干个,然后执行完了还要等结果。通常我们会怎么做呢?Handler,或者runOnUIThread。但是有没有别的选择了呢?有的,就是CountDownLatch
先来看个例子
代码语言:javascript复制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();
}
}
}
主要看着一段代码:
代码语言:javascript复制 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