就在前天我去阿里面试P7职位,面试官直接给我出了这六道多线程面试题,同步深刻思考问题,哲学家就餐问题、异步线程事务咋回滚问题、触及灵魂的同步问题、经典的线程交替问题、生产者消费者问题、下面就是我做出来的答案以及代码
Show Me The Difference (From Alibaba)
package com.mashibing.juc.c_35_QuestionsOfAlibaba;
public class ShowMeTheDifference {}
//4.指出以下两段程序的差别,并分析
final class Accumulator {
private double result = 0.0D;
public void addAll( double[] values) {
for(double value : values) {
result += value;
}
}
}
final class Accumulator2 {
private double result = 0.0D;
public void addAll( double[] values) {
double sum = 0.0D;
for(double value : values) {
sum += value;
}
result += sum;
}
}
答案:
第二种写法比第一种写法出现不一致性的概率要小,因为我们在方法完成之前,读不到中间状态的脏数据
尽量少暴露线程计算过程的中间状态
能用范围小的变量,不用范围大的变量
哲学家就餐问题
- 模拟哲学家问题 OOA - OOD - DDD
class : 哲学家 class : 筷子 - 筷子:编号
- 哲学家:左手的筷子 右手的筷子 编号
package com.mashibing.juc.c_33_TheDinningPhilosophersProblem;
import com.mashibing.util.SleepHelper;
public class T01_DeadLock {
public static void main(String[] args) {
ChopStick cs0 = new ChopStick();
ChopStick cs1 = new ChopStick();
ChopStick cs2 = new ChopStick();
ChopStick cs3 = new ChopStick();
ChopStick cs4 = new ChopStick();
Philosohper p0 = new Philosohper("p0", 0, cs0, cs1);
Philosohper p1 = new Philosohper("p1", 1, cs1, cs2);
Philosohper p2 = new Philosohper("p2", 2, cs2, cs3);
Philosohper p3 = new Philosohper("p3", 3, cs3, cs4);
Philosohper p4 = new Philosohper("p4", 4, cs4, cs0);
p0.start();
p1.start();
p2.start();
p3.start();
p4.start();
}
public static class Philosohper extends Thread {
private ChopStick left, right;
private int index;
public Philosohper(String name, int index, ChopStick left, ChopStick right) {
this.setName(name);
this.index = index;
this.left = left;
this.right = right;
}
@Override
public void run() {
synchronized (left) {
SleepHelper.sleepSeconds(1 + index);
synchronized (right) {