1 使用线程池方法:
运行效果可以看到:
2 使用countDownLatch同步工具类
CountDownLatch countDownLatch=new CountDownLatch(2);
Log.e("tanlin", "主线程开始执行");
ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor(10,10,0l,
TimeUnit.MILLISECONDS,new LinkedBlockingQueue<>());
threadPoolExecutor.submit(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
Log.e("tanlin", "子线程执行1");
countDownLatch.countDown();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
});
threadPoolExecutor.submit(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
Log.e("tanlin", "子线程执行2");
countDownLatch.countDown();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
});
try {
countDownLatch.await();
}catch (InterruptedException e) {
e.printStackTrace();
}
Log.e("tanlin", "两个子线程执行完,主线程继续执行");
这两种方式比较优雅,当然还有其他各种方式。
网友评论