吃透这几道多线程面试题,进大厂也没你们想的那么难

        就在前天我去阿里面试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;
    }
}

答案:
第二种写法比第一种写法出现不一致性的概率要小,因为我们在方法完成之前,读不到中间状态的脏数据

尽量少暴露线程计算过程的中间状态

能用范围小的变量,不用范围大的变量

哲学家就餐问题

面试阿里!我把这几道最难的多线程面试题解答出来了

  1. 模拟哲学家问题 OOA - OOD - DDD
    class : 哲学家 class : 筷子
  2. 筷子:编号
  3. 哲学家:左手的筷子 右手的筷子 编号
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) {
                  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值