Lazy loaded image
技术分享
🗒️Java面试题:多线程交替打印字符串
字数 437阅读时长 2 分钟
2020-7-8
2023-9-7
type
status
date
slug
summary
tags
category
icon
password
这道题是字节的面试题,当场问我有点紧张没想出来,只答上来要交替阻塞,还是面试官提醒我用生产者消费者思路解决。

题目

有A类线程50个,任务是打印字符A。有B类线程50个,任务是打印字符B。现在异步启动这100个线程,问如何才能让他们交替打印AB字符?

解题思路

设两个信号SemaphoreA和SemaphoreB,他们代表A类和B类的资源数且他们的上限各有一个。初始设SemaphoreA=1,SemaphoreB=0。当一个A类线程消费完SemaphoreA,生产一个B类资源:SemaphoreB++。此时其他A类线程进入阻塞,某一B线程开始获取资源打印。当一个B类线程消费完SemaphoreB,生产一个A类资源:SemaphoreA++。此后循环交替打印。该题的难点在于是否想到生产者消费者。

实践

这道题LeetCode上有,我就刷了下:https://leetcode-cn.com/problems/print-foobar-alternately/

描述

两个不同的线程将会共用一个 FooBar 实例。其中一个线程将会调用 foo() 方法,另一个线程将会调用 bar() 方法。请设计修改程序,以确保 "foobar" 被输出 n 次。

代码

class FooBar { private int n; private Semaphore semaphoreFoo = new Semaphore(1); private Semaphore semaphoreBar = new Semaphore(0); public FooBar(int n) { this.n = n; } public void foo(Runnable printFoo) throws InterruptedException { for (int i = 0; i < n; i++) { semaphoreFoo.acquire(); // printFoo.run() outputs "foo". Do not change or remove this line. printFoo.run(); semaphoreBar.release(); } } public void bar(Runnable printBar) throws InterruptedException { for (int i = 0; i < n; i++) { semaphoreBar.acquire(); // printBar.run() outputs "bar". Do not change or remove this line. printBar.run(); semaphoreFoo.release(); } } }
 
上一篇
Android面试题:Scrollview内嵌一个Button他的事件消费是怎样的?Move,Down,Up分别被哪个组件消费?
下一篇
EventBus使用初体验

评论
Loading...