1 使用線程池方法:
運(yùn)行效果可以看到:
2 使用countDownLatch同步工具類
CountDownLatch countDownLatch=new CountDownLatch(2);
Log.e("tanlin", "主線程開(kāi)始執(zhí)行");
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", "子線程執(zhí)行1");
? ? ? ? ? ? countDownLatch.countDown();
? ? ? ? }catch (InterruptedException e) {
e.printStackTrace();
? ? ? ? }
}
});
threadPoolExecutor.submit(new Runnable() {
@Override
? ? public void run() {
try {
Thread.sleep(1000);
? ? ? ? ? ? Log.e("tanlin", "子線程執(zhí)行2");
? ? ? ? ? ? countDownLatch.countDown();
? ? ? ? }catch (InterruptedException e) {
e.printStackTrace();
? ? ? ? }
}
});
try {
countDownLatch.await();
}catch (InterruptedException e) {
e.printStackTrace();
}
Log.e("tanlin", "兩個(gè)子線程執(zhí)行完,主線程繼續(xù)執(zhí)行");
這兩種方式比較優(yōu)雅腊脱,當(dāng)然還有其他各種方式。