Skip to content

Commit

Permalink
Create 你会这道阿里多线程面试题吗?.md
Browse files Browse the repository at this point in the history
  • Loading branch information
CoffeeLatte007 committed Mar 13, 2019
1 parent debeed9 commit d754a9a
Showing 1 changed file with 182 additions and 0 deletions.
182 changes: 182 additions & 0 deletions 面试经验/你会这道阿里多线程面试题吗?.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
# 背景
在前几天,群里有个群友问了我道面试阿里的时候遇到的多线程题目,这个题目比较有意思,在这里和大家分享下。

废话不多说,直接上题目:

```
通过N个线程顺序循环打印从0100,如给定N=3则输出:
thread0: 0
thread1: 1
thread2: 2
thread0: 3
thread1: 4
.....
```
些经常刷面试题的朋友,之前肯定遇到过下面这个题目:

```
两个线程交替打印0~100的奇偶数:
偶线程:0
奇线程:1
偶线程:2
奇线程:3
```
这两个题目看起来相似,第二个题目稍微来说比较简单点,大家可以先思考下两个线程奇偶数如何打印。

# 两线程奇偶数打印
些人这里可能会用讨巧的,用个线程进行循环,在每次循环里面都会做是奇数还是偶数的判断,然后打印出这个我们想要的结果。在这里我们不过多讨论这种违背题目本意的做法。

其实要做这个题目我们就需要控制两个线程的执行顺序,偶线程执行完之后奇数线程执行,这个有点像通知机制,偶线程通知奇线程,奇线程再通知偶线程。而看到通知/等待,立马就有朋友想到了Object中的waitnotify。没错,这里我们用waitnotify对其进行实现,代码如下:

```
public class 交替打印奇偶数 {
static class SoulutionTask implements Runnable{
static int value = 0;
@Override
public void run() {
while (value <= 100){
synchronized (SoulutionTask.class){
System.out.println(Thread.currentThread().getName() + ":" + value++);
SoulutionTask.class.notify();
try {
SoulutionTask.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
new Thread(new SoulutionTask(), "偶数").start();
new Thread(new SoulutionTask(), "奇数").start();
}
}
```
这里我们有两个线程,通过notifywait用来控制我们线程的执行,从而打印出我们目标的结果

# N个线程循环打印

再回到我们最初的问题来,N个线程进行循环打印,这个问题我再帮助群友解答了之后,又再次把这个问题在群里面抛了出来,不少老司机之前看过交替打印奇偶数这道题目,于是马上做出了几个版本,让我们看看老司机1的代码:

```
public class 老司机1 implements Runnable {

private static final Object LOCK = new Object();
/**
* 当前即将打印的数字
*/
private static int current = 0;
/**
* 当前线程编号,从0开始
*/
private int threadNo;
/**
* 线程数量
*/
private int threadCount;
/**
* 打印的最大数值
*/
private int maxInt;

public 老司机1(int threadNo, int threadCount, int maxInt) {
this.threadNo = threadNo;
this.threadCount = threadCount;
this.maxInt = maxInt;
}

@Override
public void run() {
while (true) {
synchronized (LOCK) {
// 判断是否轮到当前线程执行
while (current % threadCount != threadNo) {
if (current > maxInt) {
break;
}
try {
// 如果不是,则当前线程进入wait
LOCK.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
// 最大值跳出循环
if (current > maxInt) {
break;
}
System.out.println("thread" + threadNo + " : " + current);
current++;
// 唤醒其他wait线程
LOCK.notifyAll();
}
}
}

public static void main(String[] args) {
int threadCount = 3;
int max = 100;
for (int i = 0; i < threadCount; i++) {
new Thread(new 老司机1(i, threadCount, max)).start();
}
}
}

```
核心方法在run里面,可以看见和我们交替打印奇偶数原理差不多,这里将我们的notify改成了notifyAll,这里要注意下很多人会将notifyAll理解成其他wait的线程全部都会执行,其实是错误的。这里只会将wait的线程解除当前wait状态,也叫作唤醒,由于我们这里用同步锁synchronized块包裹住,那么唤醒的线程会做会抢夺同步锁。

这个老司机的代码的确能跑通,但是有个问题是什么呢?当我们线程数很大的时候,由于我们不确定唤醒的线程到底是否是下个要执行的就有可能会出现抢到了锁但不该自己执行,然后又进入wait的情况,比如现在有100个线程,现在是第个线程在执行,他执行完之后需要第二个线程执行,但是第100个线程抢到了,发现不是自己然后又进入wait,然后第99个线程抢到了,发现不是自己然后又进入wait,然后第98,97...直到第3个线程都抢到了,最后才到第二个线程抢到同步锁,这里就会白白的多执行很多过程,虽然最后能完成目标。

![](https://user-gold-cdn.xitu.io/2019/3/13/16977c0a915b0446?w=541&h=293&f=png&s=28217)

还有其他老司机用lock/condition也实现了这样的功能,还有老司机用比较新颖的方法比如队列去做,当然这里就不多提了,大致的原理都是基于上面的,这里我说下我的做法,在Java的多线程中提供了些常用的同步器,在这个场景下比较适合于使用Semaphore,也就是信号量,我们上个线程持有下个线程的信号量,通过个信号量数组将全部关联起来,代码如下:

```
static int result = 0;
public static void main(String[] args) throws InterruptedException {
int N = 3;
Thread[] threads = new Thread[N];
final Semaphore[] syncObjects = new Semaphore[N];
for (int i = 0; i < N; i++) {
syncObjects[i] = new Semaphore(1);
if (i != N-1){
syncObjects[i].acquire();
}
}
for (int i = 0; i < N; i++) {
final Semaphore lastSemphore = i == 0 ? syncObjects[N - 1] : syncObjects[i - 1];
final Semaphore curSemphore = syncObjects[i];
final int index = i;
threads[i] = new Thread(new Runnable() {

public void run() {
try {
while (true) {
lastSemphore.acquire();
System.out.println("thread" + index + ": " + result++);
if (result > 100){
System.exit(0);
}
curSemphore.release();
}
} catch (Exception e) {
e.printStackTrace();
}

}
});
threads[i].start();
}
}
```
通过这种方式,我们就不会有白白唤醒的线程,每个线程都按照我们所约定的顺序去执行,这其实也是面试官所需要考的地方,让每个线程的执行都能再你手中得到控制,这也可以验证你多线程知识是否牢固。

最后这篇文章被我收录于JGrowing-Java面试篇,个全面,优秀,由社区起共建的Java学习路线,如果您想参与开源项目的维护,可以起共建,github地址为:https://github.com/javagrowing/JGrowing
麻烦给个小星星哟。

> 如果大家觉得这篇文章对你有帮助,你的关注和转发是对我最大的支持,O(∩_∩)O:

![](https://user-gold-cdn.xitu.io/2018/7/22/164c2ad786c7cfe4?w=500&h=375&f=jpeg&s=215163)


0 comments on commit d754a9a

Please sign in to comment.