tx一面线程交替手撕

import java.util.concurrent.Semaphore;

// 交替打印   1 A  2 B 3 C 这样的线程
public class alternatingPrinter {

    public static Semaphore  text = new Semaphore(1);
    public  static  Semaphore  word=new Semaphore(0);
    public static   int maxText=3;
    public static  int maxWord='c';
    
    public static void main(String[] args) {
          Thread thread1=new Thread(new printerText());
          Thread thread2=new Thread(new printerWord());
          thread2.start();
          thread1.start();
    }
    static  class  printerText implements Runnable  {

        @Override
        public void run() {
            for (int i = 1; i <=maxText; i++) {
                try {
                    text.acquire();
                    System.out.println(i);
                    word.release();
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    static  class  printerWord implements  Runnable{

        @Override
        public void run() {
            for (int i = 'A'; i <=maxWord ; i++) {
               try {
                   //会一直等待这个信号量
                   word.acquire();
                   System.out.println((char)i);
                   text.release();
               }catch (InterruptedException e){
                   e.printStackTrace();
               }
            }
        }
    }
}

通过信号量来控制两个线程打印的顺序问题。

如果两个线程打印的长度不匹配, A1 B 2 C 3 D EF 这样的形式呢?

通过定义两个变量 boolean 类型的用来判断是否结束,如果结束了,如果对方结束了直接打印即可,就不用再释放锁了。


import java.util.concurrent.Semaphore;

// 交替打印   1 A  2 B 3 C 这样的线程
public class alternatingPrinter {

    public static Semaphore  text = new Semaphore(1);
    public  static  Semaphore  word=new Semaphore(0);

    public static   int maxText=10;
    public static  int maxWord='C';
    public  static  boolean isText=false;
    public  static  boolean isWord=false;
    public static void main(String[] args) {

        Thread thread1=new Thread(new printerText());
        Thread thread2=new Thread(new printerWord());

        thread2.start();
        thread1.start();
    }

    static  class  printerText implements Runnable  {

        @Override
        public void run() {
            for (int i = 1; i <=maxText; i++) {
                try {
                    if (isWord){
                        System.out.println(i);
                        continue;
                    }
                    text.acquire();
                    System.out.println(i);
                    word.release();
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            isText=true;
            text.release();
        }
    }
    static  class  printerWord implements  Runnable{
        @Override
        public void run() {
            for (int i = 'A'; i <=maxWord ; i++) {
                try {
                    //会一直等待这个信号量
                    if (isText){
                        System.out.println(i);
                        continue;
                    }
                    word.acquire();
                    System.out.println((char)i);
                    text.release();
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
            isWord=true;
            word.release();
        }
    }
}

可重入锁是什么,可以使用可重入锁来实现交替打印吗?

可重入锁是允许同一个线程多次获得同一把锁的同步机制。

后台通过定义计数器来实现,释放锁的时候计数器递减,只有计数器为 0 的时候才是真正的释放。

在 Java 中主要是 ReentantLock 类,实现可重入锁,手动的进行 lock 和 unlock,实现细粒度的锁机制。

直接用 lock 无法控制两个线程交替打印,需要通过 Condition 来实现。

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

 class alternatingPrinter2 {

    // 创建可重入锁及两个 Condition
    private static ReentrantLock lock = new ReentrantLock();
    // 数字线程等待条件
    private static Condition conditionNumber = lock.newCondition();
    // 字母线程等待条件
    private static Condition conditionLetter = lock.newCondition();
  
    private static boolean numberTurn = true;

    private static final int MAX_NUMBER = 3; // 打印数字 1~3
    private static final int MAX_LETTER = 'C'; // 打印字母 A~C

    public static void main(String[] args) {
        Thread threadNumber = new Thread(new NumberPrinter());
        Thread threadLetter = new Thread(new LetterPrinter());

        threadNumber.start();
        threadLetter.start();
    }

    // 打印数字的线程
    static class NumberPrinter implements Runnable {
        @Override
        public void run() {
            for (int i = 1; i <= MAX_NUMBER; i++) {
                lock.lock();
                try {
                    // 如果不是数字打印的时机,则等待
                    while (!numberTurn) {
                        conditionNumber.await();
                    }
                    // 打印数字
                    System.out.print(i + " ");
                    // 修改标志,轮到字母线程打印
                    numberTurn = false;
                    // 通知字母线程
                    conditionLetter.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }
    // 打印字母的线程
    static class LetterPrinter implements Runnable {
        @Override
        public void run() {
            for (char c = 'A'; c <= (char) MAX_LETTER; c++) {
                lock.lock();
                try {
                    while (numberTurn) {
                        conditionLetter.await();
                    }
                    System.out.print(c + " ");
          
                    numberTurn = true;
      
                    conditionNumber.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }
}
#交替打印#
牛牛的算法专栏 文章被收录于专栏

牛牛的算法专栏,记录一些算法题

全部评论
很妙
点赞 回复 分享
发布于 2025-04-23 12:10 广东

相关推荐

不愿透露姓名的神秘牛友
2025-12-04 02:00
offer1:字节跳动(北京)-&nbsp;后端开发岗-&nbsp;薪资:总包42w(基本工资30w+绩效6w+年终奖6w),15薪,加班费按法定标准发放-&nbsp;福利:公积金按12%缴纳,无宿舍,每月住房补贴2000元,餐补1500元,每年2次体检,免费健身房-&nbsp;工作强度:996是常态,忙的时候可能到凌晨,团队节奏快,压力大-&nbsp;其他:平台大,技术氛围浓,晋升路径清晰,对转行选手来说履历加分多,但北京生活成本高,租房压力大offer2:美团(上海)-&nbsp;客户端开发岗-&nbsp;薪资:总包38w(基本工资26w+绩效5w+年终奖7w),14薪,加班无加班费,可调休-&nbsp;福利:公积金按10%缴纳,无宿舍,每月住房补贴1800元,餐补800元,每年1次体检,节日福利丰富-&nbsp;工作强度:995为主,偶尔周末加班,项目紧急时会通宵,整体压力中等-&nbsp;其他:公司业务成熟,行业地位稳固,客户端岗位需求稳定,上海生活节奏比北京稍缓,但租房成本仍较高offer3:网易(杭州)-&nbsp;测试开发岗-&nbsp;薪资:总包32w(基本工资22w+绩效4w+年终奖6w),13薪,加班较少,无加班费-&nbsp;福利:公积金按12%缴纳,提供员工宿舍(单人间,前两年免费,第三年按市场价5折),每月餐补1000元,每年1次体检+1次旅游补贴-&nbsp;工作强度:965为主,几乎无强制加班,团队氛围轻松,摸鱼文化盛行-&nbsp;其他:杭州生活成本低于北上,宿舍省房租,测试开发岗入门难度低,适合转行过渡,但技术成长速度可能不如开发岗,未来跳槽竞争力未知本人情况:传统工科转行,编程基础一般,想快速提升技术能力,同时也希望工作生活能平衡,未来不确定是否留在一线城市。有没有同款转行选手或互联网前辈给点建议呀?
森七菜:梦到什么说什么属于是
点赞 评论 收藏
分享
评论
2
9
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务