【Java】有 A、B、C 三个线程,如何保证三个线程同时执行?在并发情况下,如何保证三个线程依次执行?如何保证三个线程有序交错执行?

您所在的位置:网站首页 三个线程交替有序打印1-100 【Java】有 A、B、C 三个线程,如何保证三个线程同时执行?在并发情况下,如何保证三个线程依次执行?如何保证三个线程有序交错执行?

【Java】有 A、B、C 三个线程,如何保证三个线程同时执行?在并发情况下,如何保证三个线程依次执行?如何保证三个线程有序交错执行?

2023-09-18 04:51| 来源: 网络整理| 查看: 265

Q1:有 A、B、C 三个线程,如何保证三个线程同时执行? Q2:有 A、B、C 三个线程,在并发情况下,如何保证三个线程依次执行? Q3:有 A、B、C 三个线程,如何保证三个线程有序交错执行? 这三个题目都是控制多个线程执行的顺序。这一类题目除了通过一些判断来完成,大多数情况下是通过 锁 来控制顺序的。

Q1:有 A、B、C 三个线程,如何保证三个线程同时执行? /** * 使用倒计时锁 CountDownLatch 实现让三个线程同时执行 */ public void function1() { ExecutorService executorService = Executors.newCachedThreadPool(); CountDownLatch countDownLatch = new CountDownLatch(1); executorService.submit(() -> { try { countDownLatch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("线程 A 执行,执行时间:" + System.currentTimeMillis()); }); executorService.submit(() -> { try { countDownLatch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("线程 B 执行,执行时间:" + System.currentTimeMillis()); }); executorService.submit(() -> { try { countDownLatch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("线程 C 执行,执行时间:" + System.currentTimeMillis()); }); countDownLatch.countDown(); }

打印结果如下,通过时间可以证明三个线程是同时执行的。

在这里插入图片描述

🎯 让三个线程同时执行,也可以使用栅栏 CyvlivBarrier 来实现,当三个线程都到达栅栏处,才开始执行。

Q2:有 A、B、C 三个线程,在并发情况下,如何保证三个线程依次执行?

要保证三个线程依次执行,也就是说,线程 A 执行完之后,才执行线程 B;线程 B 执行完之后,才执行线程 C 有两个方法可以实现顺序执行:volatile 和 倒计时锁 CountDownLatch

private volatile int count = 0; /** * 使用一个变量进行判断执行哪个线程。没有轮到的线程在不停循环,没有停止线程 */ public void useVolatile() { ExecutorService executorService = Executors.newCachedThreadPool(); executorService.submit(() -> { while (true) { if (count == 0) { for (int i = 0; i while (true) { if (count == 1) { for (int i = 0; i while (true) { if (count == 2) { for (int i = 0; i ExecutorService executorService = Executors.newCachedThreadPool(); CountDownLatch ALatch = new CountDownLatch(1); CountDownLatch BLatch = new CountDownLatch(1); CountDownLatch CLatch = new CountDownLatch(1); executorService.submit(() -> { try { ALatch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } for (int i = 0; i try { BLatch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } for (int i = 0; i try { CLatch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } for (int i = 0; i new Thread(() -> { try { lock.lock(); for (int i = 0; i e.printStackTrace(); } finally { lock.unlock(); } }).start(); new Thread(() -> { try { lock.lock(); for (int i = 0; i e.printStackTrace(); } finally { lock.unlock(); } }).start(); new Thread(() -> { try { lock.lock(); for (int i = 0; i e.printStackTrace(); } finally { lock.unlock(); } }).start(); }

通过打印结果可以看出,线程 A、B、C 相互交错执行。

A - 0 B - 0 C - 0 A - 1 B - 1 C - 1 A - 2 B - 2 C - 2 A - 3 B - 3 C - 3 A - 4 B - 4 C - 4


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3