Java实现两个线程交替打印的六种方式

本文展示了Java中几种不同的并发控制机制,包括使用CAS自旋实现无锁操作,synchronized配合标志位进行同步,公平锁结合条件队列,利用阻塞队列实现线程间通信,通过信号量控制资源访问,以及使用CyclicBarrier协调多线程间的协作。每种方法都用于确保A和B交替打印,体现了不同并发策略的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.CAS+自旋

public class Test {
    public static void main(String[] args) throws Exception {
        AtomicBoolean isA = new AtomicBoolean(true);
        new Thread(() -> {
            for (int i = 0; i < 10; ) {
                while (isA.get()) {
                    System.out.print("A");
                    i++;
                    isA.set(false);
                }
                Thread.yield();
            }
        }).start();
        new Thread(() -> {
            for (int i = 0; i < 10; ) {
                while (!isA.get()) {
                    System.out.print("B");
                    i++;
                    isA.set(true);
                }
                Thread.yield();
            }
        }).start();

    }
}

2.synchronized+标志位

public class Test {
    public static void main(String[] args) throws Exception {
        Object lock = new Object();
        AtomicBoolean isA = new AtomicBoolean(true);
        new Thread(() -> {
            for (int i = 0; i < 10;) {
                synchronized (lock){
                    while (!isA.get()) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.print("A");
                    i++;
                    isA.set(false);
                    lock.notifyAll();
                }
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 10;) {
                synchronized (lock) {
                    while (isA.get()) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.print("B");
                    i++;
                    isA.set(true);
                    lock.notifyAll();
                }
            }
        }).start();

    }
}

3.lock公平锁+条件队列+标志位

public class Test {
    public static void main(String[] args) throws Exception {
        ReentrantLock lock = new ReentrantLock(true);
        Condition condition = lock.newCondition();
        AtomicBoolean isA = new AtomicBoolean(true);
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {

                lock.lock();
                try {
                    while (!isA.get()) {
                        //不是自己打印的标志就释放锁
                        try {
                            condition.await();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.print("A");
                    isA.set(false);
                    condition.signalAll();
                } finally {
                    lock.unlock();
                }
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                lock.lock();
                try {
                    while (isA.get()) {
                        //不是自己打印的标志就释放锁
                        try {
                            condition.await();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.print("B");
                    isA.set(true);
                    condition.signalAll();
                } finally {
                    lock.unlock();
                }
            }
        }).start();

    }
}

4.阻塞队列

public class Test {
    public static void main(String[] args) {
        BlockingQueue<Integer> queueA = new LinkedBlockingQueue<>(1);
        BlockingQueue<Integer> queueB = new LinkedBlockingQueue<>(1);
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    queueA.put(i);
                    System.out.print("A");
                    queueB.put(i);
                }catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    queueB.take();
                    System.out.print("B");
                    queueA.take();
                }catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }
}

5.信号量

public class Test {
    public static void main(String[] args) {
        Semaphore semaphoreA = new Semaphore(1);
        Semaphore semaphoreB = new Semaphore(0);
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    semaphoreA.acquire();
                    System.out.print("A");
                    semaphoreB.release();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    semaphoreB.acquire();
                    System.out.print("B");
                    semaphoreA.release();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        }).start();
    }
}

6.CyclicBarrier等待

public class Test {
    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(2);//循环的countdownLatch
        AtomicBoolean isA = new AtomicBoolean(true);
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                while (!isA.get()) {
                }
                System.out.print("A");
                isA.set(false);
                try {
                    barrier.await();//等待所有线程执行完
                } catch (InterruptedException | BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                while (isA.get()) {
                }
                System.out.print("B");
                isA.set(true);
                try {
                    barrier.await();//等待所有线程执行完
                } catch (InterruptedException | BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值