线程异步转同步

2021-02-23  本文已影响0人  浩仔_Boy

学习笔记,仅供自己参考,如有不对欢迎指正

5.T1、T2、T3三个线程,如何保证它们顺序执行?也就是异步转同步的方式。

package com.zhboy.myapplication;

import android.util.Log;
import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * @author zhou_hao
 * @date 2020/12/25
 * @description: 异步转同步的方式
 */
public class AsyncQuery {

    private static final String LOGGER_NAME = AsyncQuery.class.getName();

    public void asyncQuery() {
        final CountDownLatch latch = new CountDownLatch(1);

        new Thread(() -> {
            int room = new Random().nextInt(10);
            try {
                Thread.sleep(room * 100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.d(LOGGER_NAME, "子线程" + Thread.currentThread().getName() + "执行完毕");
            latch.countDown();
        }).start();

        try {
            latch.await();//等待
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

测试:

  Log.d("AsyncQuery", "执行查询")
        for (i in 0..10){
            val asyncQuery = AsyncQuery()
            asyncQuery.asyncQuery()
        }
        Log.d("AsyncQuery", "查询结束-执行主线程")

结果:

image.png
上一篇下一篇

猜你喜欢

热点阅读