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

在多线程的面试中,经常会遇到三个类似的线程执行问题:
Q1:有 A、B、C 三个线程,如何保证三个线程同时执行?
Q2:有 A、B、C 三个线程,在并发情况下,如何保证三个线程依次执行?
Q3:有 A、B、C 三个线程,如何保证三个线程有序交错执行?

Q1:有 A、B、C 三个线程,如何保证三个线程同时执行?

保证线程同时执行可以用于并发测试。可以使用倒计时锁CountDownLatch实现让三个线程同时执行。代码如下所示:

        ExecutorService executorService = Executors.newCachedThreadPool();
        CountDownLatch countDownLatch = new CountDownLatch(1);

        executorService.submit(()->{
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("线程A执行,执行时间:" + System.currentTimeMillis());
        });

        executorService.submit(()->{
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("线程B执行,执行时间:" + System.currentTimeMillis());
        });

        executorService.submit(()->{
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("线程C执行,执行时间:" + System.currentTimeMillis());
        });

        countDownLatch.countDown();

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

线程A执行,执行时间:1617811258309
线程C执行,执行时间:1617811258309
线程B执行,执行时间:1617811258309

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

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

  1. 用 join 方法

使用 join() 方法可以保证线程的顺序执行。在 Java 中,join() 方法是用来等待一个线程执行完成的方法,当调用某个线程的 join() 方法时,当前线程会被阻塞,直到该线程执行完成后才会继续执行。

具体来说,我们可以在 T1 线程结束时调用 T2 的 join() 方法,这样 T2 就会等待 T1 执行完成后再开始执行;同理,在 T2 结束时调用 T3 的 join() 方法,以确保 T3 在 T2 执行完成后才开始执行。这样就可以保证 T1、T2、T3 按照顺序依次执行。

  1. 使用CountDownLatch(闭锁)

使用 CountDownLatch(闭锁)方法可以保证线程的顺序执行。CountDownLatch 是一个同步工具类,它可以让某个线程等待多个线程完成各自的工作之后再继续执行。

@Test
    public void testUseCountDownLatch() {
        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) {
                e.printStackTrace();
            }

            for (int i = 0; i < 10; i++) {
                System.out.println("A - " + i);
            }

            bLatch.countDown();
        });

        executorService.submit(() -> {
            try {
                bLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            for (int i = 0; i < 10; i++) {
                System.out.println("B - " + i);
            }

            cLatch.countDown();
        });

        executorService.submit(() -> {
            try {
                cLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            for (int i = 0; i < 10; i++) {
                System.out.println("C - " + i);
            }
        });

        aLatch.countDown();
    }

执行结果:

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

  1. volatile 使用一个变量进行判断执行哪个线程。没有轮到的线程在不停循环,没有停止线程
private volatile int count = 0;

/**
 * 使用一个变量进行判断执行哪个线程。没有轮到的线程在不停循环,没有停止线程
 */
public void useVolatile() {

    ExecutorService executorService = Executors.newCachedThreadPool();

    executorService.submit(() -> {
        while (true) {
            if (count == 0) {
                for (int i = 0; i < 5; i++) {
                    System.out.println("A - " + i);
                }
                count = 1;
                break;
            }
        }
    });

    executorService.submit(() -> {
        while (true) {
            if (count == 1) {
                for (int i = 0; i < 5; i++) {
                    System.out.println("B - " + i);
                }
                count = 2;
                break;
            }
        }
    });

    executorService.submit(() -> {
        while (true) {
            if (count == 2) {
                for (int i = 0; i < 5; i++) {
                    System.out.println("C - " + i);
                }
                count = 3;
                break;
            }
        }
    });
}
  1. 使用单个线程池

使用单个线程池可以保证t1、t2、t3顺序执行,因为单个线程池只有一个工作线程每次只会执行一个任务。我们可以将t1、t2、t3三个任务按照顺序提交给单个线程池,这样就可以确保它们按照顺序依次执行。

Q3:有 A、B、C 三个线程,如何保证三个线程有序交错执行?

实现三个线程交错打印,可以使用ReentrantLock以及3个Condition来实现,代码如下所示:

package com.wangguitang.freedom.interview.concurrent;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;


public class ThreeThreadsAlternatePrint {

    private static final ReentrantLock lock = new ReentrantLock();
    private static Condition c1 = lock.newCondition();
    private static Condition c2 = lock.newCondition();
    private static Condition c3 = lock.newCondition();

    
    public static void main(String[] args) {

        new Thread(() -> {
            try {
                lock.lock();

                for (int i = 0; i < 10; i++) {
                    System.out.println("A - " + i);
                    c2.signal();
                    c1.await();
                }

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

        new Thread(() -> {
            try {
                lock.lock();

                for (int i = 0; i < 10; i++) {
                    System.out.println("B - " + i);
                    c3.signal();
                    c2.await();
                }

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

        new Thread(() -> {
            try {
                lock.lock();

                for (int i = 0; i < 10; i++) {
                    System.out.println("C - " + i);
                    c1.signal();
                    c3.await();
                }

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

    }
}

执行结果:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用Java中的Thread类和Runnable接口来创建和运行线程。下面是一个实现上述要求的示例代码: ```java public class MultiThreadExample { public static void main(String[] args) { Thread threadA = new Thread(new PrintLetterTask('a', 100)); Thread threadB = new Thread(new PrintLetterTask('b', 100)); Thread threadC = new Thread(new PrintNumberTask(100)); threadA.start(); threadB.start(); threadC.start(); } } class PrintLetterTask implements Runnable { private char letter; private int count; public PrintLetterTask(char letter, int count) { this.letter = letter; this.count = count; } @Override public void run() { for (int i = 0; i < count; i++) { System.out.print(letter); } } } class PrintNumberTask implements Runnable { private int count; public PrintNumberTask(int count) { this.count = count; } @Override public void run() { for (int i = 1; i <= count; i++) { System.out.print(i + " "); } } } ``` 在上述代码中,我们定义了两个实现了Runnable接口的任务类PrintLetterTask和PrintNumberTask,分别用于打印字母和数字。在主函数中,我们创建了三个线程,每个线程分别执行一个任务。最后,我们调用start()方法启动这三个线程,让它们并发执行任务。运行程序后,会看到输出结果如下: ``` aabb1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 ``` 可以看到,三个线程分别执行了各自的任务,并且输出结果是交错的,符合并发执行的特点。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值