三个线程,按序打印10次ABC

本文通过三种不同的同步策略——使用ReentrantLock、Semaphore和Condition,详细解释如何在Java中实现三个线程按序打印10次ABC。每个线程分别负责打印'A'、'B'、'C',通过锁和同步机制确保打印顺序的正确性。示例代码展示了如何避免线程竞争并实现线程间的协调通信,达到预期的打印效果。

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

题目

跟标题一样,就是依次打印10次ABC,不过是由三个线程来完成的,这个时候就要考虑到那些线程之间的竞争问题!

思路1

可以lock锁,三个线程共同竞争一把锁,竞争到了而且是属于自己该打印的就去打印!

代码1

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

public class  Main{
    private static Lock  lock = new ReentrantLock();
    private static int state = 0;
    public static void main(String[] args)
    {
        new Thread(new ThreadA()).start();
        new Thread(new ThreadB()).start();
        new Thread(new ThreadC()).start();
    }
    static class ThreadA implements Runnable
    {
        @Override
        public void run() {
            for (int i=0;i<10;)
            {
                try
                {
                    lock.lock();//上锁
                    while (state%3==0)
                    {
                        System.out.println("A");
                        ++state;
                        ++i;
                    }
                }
                finally
                {
                    lock.unlock(); // 解锁
                }
            }
        }
    }

    static class ThreadB implements Runnable
    {

        @Override
        public void run() {
            for (int i=0;i<10;)
            {
                try
                {
                    lock.lock();
                    while (state%3==1)
                    {
                        System.out.println("B");
                        ++state;
                        ++i;
                    }
                }
                finally {
                    lock.unlock();
                }
            }
        }
    }

    static class ThreadC implements Runnable
    {
        @Override
        public void run()
        {
            for (int i=0;i<10;)
            {
                try
                {
                    lock.lock();
                    while (state%3==2)
                    {
                        System.out.println("C");
                        ++state;
                        ++i;
                    }
                }
                finally
                {
                    lock.unlock();
                }

            }
        }
    }
}

结果1

这样子是可以的,利用锁和一个变量,无论是谁竞争到锁,但是如果state不是自己对应的线程该打印的,那么这把锁也会被释放掉!然后,几个进程再去竞争同一把锁,直到竞争到锁的线程刚刚好需要打印,按序就可以完成打印的功能!

思路2

跟上面加锁差不多,这里利用信号量来做线程同步!

代码2

import java.util.concurrent.Semaphore;

public class  Main{
    private static Semaphore semaphore = new Semaphore(1);//只有一个线程可以获得这个资源
    private static int state = 0;
    public static void main(String[] args) {
        new Thread(new ThreadA()).start();
        new Thread(new ThreadB()).start();
        new Thread(new ThreadC()).start();
    }

    static class ThreadA  implements Runnable
    {
        @Override
        public void run()
        {
            for (int i=0;i<10;)
            {
                try
                {
                 semaphore.acquire();
                 while (state%3==0)
                 {
                     System.out.println("A");
                     ++state;
                     ++i;
                 }
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                finally
                {
                    semaphore.release();
                }
            }
        }
    }
    static class ThreadB implements Runnable{
        @Override
        public void run() {
            for (int i=0;i<10;)
            {
                try
                {
                    semaphore.acquire();
                    while (state%3==1)
                    {
                        System.out.println("B");
                        ++state;
                        ++i;
                    }
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                finally {
                    semaphore.release();
                }
            }
        }
    }
    static class ThreadC implements Runnable{
        @Override
        public void run()
        {
            for (int i=0;i<10;)
            {
                try
                {
                    semaphore.acquire();
                    while (state%3==2)
                    {
                        System.out.println("C");
                        ++state;
                        ++i;
                    }
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                finally
                {
                    semaphore.release();
                }
            }
        }
    }
}

结果2

也是能够正常按序打印!

思路3

利用lock锁和condition监视器,因为这个监视器可以唤醒特定的线程(await()和signal()),相比于wait()和notify()有更大的优势!

代码3

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

public class  Main{
    private static Lock lock = new ReentrantLock();
    private static Condition condition1 = lock.newCondition();
    private static Condition condition2 = lock.newCondition();
    private static Condition condition3 = lock.newCondition();
    private static int number = 1;
    public static void main(String[] args) {
        new Thread(new ThreadA()).start();
        new Thread(new ThreadB()).start();
        new Thread(new ThreadC()).start();
    }
    static class ThreadA implements Runnable
    {
        @Override
        public void run() {
            for (int i=0;i<10;)
            {
                try
                {
                    lock.lock();
                    while (number!=1)
                        condition1.await();
                    number=2;
                    ++i;
                    System.out.println("A");
                    condition2.signal();
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                } finally
                {
                    lock.unlock();
                }

            }
        }
    }

    static class ThreadB implements Runnable{

        @Override
        public void run() {
            for (int i=0;i<10;)
            {
                try
                {
                    lock.lock();
                    while (number!=2)
                    {
                        condition2.await();
                    }
                    number=3;
                    ++i;
                    System.out.println("B");
                    condition3.signal();
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    static class ThreadC implements Runnable{

        @Override
        public void run() {
            for (int i=0;i<10;)
            {
                try
                {
                    lock.lock();
                    while (number!=3)
                        condition3.await();
                    number=1;
                    ++i;
                    System.out.println("C");
                    condition1.signal();
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                finally {
                    lock.unlock();
                }
            }
        }
    }
}

结果3

这种也是能够正常按照顺序输出10次ABC的!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值