• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
gaohuan30
博客园    首页    新随笔    联系   管理    订阅  订阅
实现两个线程顺序依次打印元素
public class L_ConditionTest {
    public static void main(String[] args) {
        L_ConditionTest t = new L_ConditionTest();
        // 这两个方法都有问题,假设两个打印的数组长度不对称,那会造成一个线程始终卡死
        t.test();
        t.test2();
        // 那么假设两个数组长度不一致,那该如何处理呢??
    }
    /**
     * 使用 SynchronousQueue 进行线程阻塞
     */
    private void test2() {
        char[] number = "12345678".toCharArray();
        char[] word = "ABCDEfgh".toCharArray();
        SynchronousQueue<String> queue = new SynchronousQueue<>();
        new Thread(() -> {

            for (char c : number) {
                System.out.print(c);
                try {
                    queue.put("X");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 先释放对方 在阻塞自己
            }

        }, "t1").start();

        new Thread(() -> {

            for (char c : word) {
                try {
                    queue.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.print(c);
            }

        }, "t2").start();
    }

    /**
     * 使用ReentrantLock 的 Condition 
     */
    private void test() {
        char[] number = "123456789".toCharArray();
        char[] word = "ABCDEfgh".toCharArray();
        Lock lock = new ReentrantLock();
        Condition numberCondition = lock.newCondition();
        Condition wordCondition = lock.newCondition();

        new Thread(() -> {

            lock.lock();
            try {
                for (char c : number) {
                    System.out.print(c);
                    // 先释放对方 在阻塞自己
                    wordCondition.signalAll();
                    numberCondition.await();
                }
                wordCondition.signalAll();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "t1").start();

        new Thread(() -> {
            lock.lock();
            try {
                for (char c : word) {
                    System.out.print(c);
                    numberCondition.signalAll();
                    wordCondition.await();
                }
                numberCondition.signalAll();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        }, "t2").start();

    }
}
posted on 2020-07-03 23:07  gaohuan30  阅读(322)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3