Java非算法手撕实现

还没写完,慢慢更

1.多线程交替打印:打印内容为ABC循环或者交替打印一段话

import java.util.concurrent.Semaphore;

public class ThreadExample {
    public static Semaphore semaphore1 = new Semaphore(1);
    public static Semaphore semaphore2 = new Semaphore(0);
    public static Semaphore semaphore3 = new Semaphore(0);

    public static void main(String[] args) {
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        semaphore1.acquire();
                        System.out.println("A");
                        semaphore2.release();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });
        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        semaphore2.acquire();
                        System.out.println("B");
                        semaphore3.release();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });
        Thread threadC = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        semaphore3.acquire();
                        System.out.println("C");
                        semaphore1.release();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });
        threadA.start();
        threadB.start();
        threadC.start();
    }
}

    2. 多线程场景题:有5个人,在那赛跑,请你设计一个多线程的裁判程序给出他们赛跑的结果顺序,5个人的速度随机处理


import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchExample1 {
    public volatile static Integer num = 0;
    public static String[] res = new String[5];
    private static final int threadCount = 5;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        final CountDownLatch countDownLatch = new CountDownLatch(threadCount);
        Random random = new Random();
        for (int i = 0; i < threadCount; i++) {
            final int threadnum = i;
            threadPool.execute(() -> {
                try {
                    int sleepTime = random.nextInt(401) + 100;
                    Thread.sleep(sleepTime);
                    res[num++] = "运动员" + (threadnum + 1) + "消耗的时间为" + sleepTime;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        threadPool.shutdown();
        for (String re : res) {
            System.out.println(re);
        }
    }
}

    3. 手写线程池(实现一个简易线程池)

    实现简易线程池,首先定义接口,主要包括,线程池基本功能,拒绝策略,线程池工厂,等待的任务队列。以及自定义异常,然后实现线程池的基本功能。

    线程池基本功能接口


public interface ThreadPool {
    //提交任务到线程池
    void execute(Runnable runnable);

    //关闭
    void shutdown();

    //获取线程池初始化时的线程大小
    int getInitSize();

    //获取线程池最大线程数
    int getMaxSize();

    //获取线程池核心线程数量
    int getCoreSize();

    //获取活跃线程数量
    int getActiveCount();

    //获取线程池缓存队列大小
    int getQueueSize();

    //查看线程是否被销毁
    boolean isShutdown();

}

拒绝策略接口

@FunctionalInterface
//这个类定义了当缓存队列达到上限的时候,将通过什么方式来通知提交者,实现了默认的三种方法
public interface DenyPolicy {
    void reject(Runnable runnable, ThreadPool threadPool);
}

线程池工厂接口

@FunctionalInterface
//创建线程的工厂
public interface ThreadFactory {

    Thread creatThread(Runnable runnable);
}

任务队列接口

//缓存提交到线程池的队列任务
public interface RunnableQueue {
    //新线程进来时,提交任务到缓存队列
    void offer(Runnable runnable);

    //取出线程
    Runnable take();

    //获取队列中线程的数量
    int size();
}

自定义异常

//自定义异常
public class RunnableDenyException extends RuntimeException {
    public RunnableDenyException(String msg) {
        super(msg);
    }
}

拒绝策略实现。(三个拒绝策略)

    //直接丢弃线程,什么都不做,不通知
    class DiscardDenyPolicy implements DenyPolicy {

        @Override
        public void reject(Runnable runnable, ThreadPool threadPool) {

        }
    }

    //抛出异常通知
    class AbortDenyPolicy implements DenyPolicy {

        @Override
        public void reject(Runnable runnable, ThreadPool threadPool) {
            throw new RunnableDenyException("这个线程:" + runnable + " 将会被丢弃");
        }
    }

    //使线程在提交者所在的线程中运行
    class RunnerDenyPolicy implements DenyPolicy {
        @Override
        public void reject(Runnable runnable, ThreadPool threadPool) {
            if (!threadPool.isShutdown()) {
                runnable.run();
            }
        }
    }

任务队列实现


import java.util.LinkedList;

public class LinkedRunnableQueue implements RunnableQueue {
    //任务队列的最大容量
    private final int limit;
    //容量最大时,需要使用的拒绝策略
    private final DenyPolicy denyPolicy;
    //存放任务的队列
    private final LinkedList<Runnable> runnableLinkedList;
    private final ThreadPool threadPool;

    public LinkedRunnableQueue(int limit, DenyPolicy denyPolicy, ThreadPool threadPool) {
        this.limit = limit;
        this.denyPolicy = denyPolicy;
        this.threadPool = threadPool;
        runnableLinkedList = new LinkedList<>();
    }

    @Override
    public void offer(Runnable runnable) {
        synchronized (runnableLinkedList) {
            //如果缓存数量超过最大值,则使用拒绝策略
            if (runnableLinkedList.size() >= limit) {
                denyPolicy.reject(runnable, threadPool);
            } else {
                //成功加入list的末尾,并唤醒阻塞中的线程
                runnableLinkedList.addLast(runnable);
                runnableLinkedList.notifyAll();
            }
        }
    }

    @Override
    public Runnable take() {
        synchronized (runnableLinkedList) {
            //如果缓存队列为空,则挂起,等待新的任务进来唤醒
            while (runnableLinkedList.isEmpty()) {
                try {
                    runnableLinkedList.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return runnableLinkedList.removeFirst();
    }

    @Override
    public int size() {
        synchronized (runnableLinkedList) {
            //返回list中的个数
            return runnableLinkedList.size();
        }
    }
}

线程工厂实现

import java.util.concurrent.atomic.AtomicInteger;

class DefaultThreadFactory implements ThreadFactory {
    private static final AtomicInteger GROUP_COUNTER = new AtomicInteger(1);
    private static final ThreadGroup group = new ThreadGroup("我的线程-" +
            GROUP_COUNTER.getAndDecrement());
    private static final AtomicInteger COUNTER = new AtomicInteger(0);

    @Override
    public Thread creatThread(Runnable runnable) {
        return new Thread(group, runnable, "线程池-" + COUNTER.getAndDecrement());
    }
}

线程池实现


import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

public class BasicThreadPool extends Thread implements ThreadPool {
    //初始化线程池的数量
    private final int initSize;
    //线程池最大线程数
    private final int maxSize;
    //线程池核心线程数
    private final int coreSize;
    //当前活跃线程的数量
    private int activeCount;
    //创建线程的工厂
    private final ThreadFactory threadFactory;
    //任务队列
    private final RunnableQueue runnableQueue;
    //线程是否被摧毁
    private volatile boolean isShutdown = false;
    //工作队列
    private final Queue<ThreadTask> internalTasks = new ArrayDeque<>();
    //拒绝策略
    private final static DenyPolicy DEFAULT_DENY_POLICY = new DiscardDenyPolicy();
    //看下面,自定义线程工厂
    private final static ThreadFactory DEFAULT_THREAD_FACTORY =
            new DefaultThreadFactory();
    private final long keepAliveTime;
    private final TimeUnit timeUnit;


    //构造默认线程池时需要传入的参数:初始线程池的数量,最大线程的数量,核心线程数量,任务队列的最大数
    public BasicThreadPool(int initSize, int maxSize, int coreSize,
                           int queueSize) {
        this(initSize, maxSize, coreSize, DEFAULT_THREAD_FACTORY,
                queueSize, DEFAULT_DENY_POLICY, 2,
                TimeUnit.SECONDS);
    }

    public BasicThreadPool(int initSize, int maxSize, int coreSize, ThreadFactory threadFactory, int queueSize,
                           DenyPolicy denyPolicy, long keepAliveTime, TimeUnit timeUnit) {
        this.initSize = initSize;
        this.maxSize = maxSize;
        this.coreSize = coreSize;
        this.threadFactory = threadFactory;
        this.runnableQueue = new LinkedRunnableQueue(queueSize, denyPolicy, this);
        this.keepAliveTime = keepAliveTime;
        this.timeUnit = timeUnit;
        this.init();
    }

    //初始化线程池并创建initSize个线程
    private void init() {
        //继承了Thread类,初始化时先启动自己
        start();
        IntStream.range(0, initSize).forEach(i -> newThread());
    }

    //创建新的任务线程并启动
    private void newThread() {
        InternalTask internalTask = new InternalTask(runnableQueue);
        Thread thread = this.threadFactory.creatThread(internalTask);
        ThreadTask threadTask = new ThreadTask(thread, internalTask);
        internalTasks.offer(threadTask);
        this.activeCount++;
        thread.start();
    }

    private void removeThread() {
        ThreadTask threadTask = internalTasks.remove();
        threadTask.internalTask.stop();
        this.activeCount--;
    }

    @Override
    public void execute(Runnable runnable) {
        if (this.isShutdown) {
            throw new IllegalStateException("这个线程池已经被销毁了");
        }
        this.runnableQueue.offer(runnable);
    }

    @Override
    public void run() {
        //自动维护线程池
        while (!isShutdown && !isInterrupted()) {
            try {
                timeUnit.sleep(keepAliveTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
                isShutdown = true;
                break;
            }
            synchronized (this) {
                if (isShutdown) {
                    break;
                }
                //当任务队列大于0,活跃线程小于核心线程的时候,扩容线程
                if (runnableQueue.size() > 0 && activeCount < coreSize) {
                    IntStream.range(initSize, coreSize).forEach(i -> newThread());
                    continue;
                }
                if (runnableQueue.size() > 0 && activeCount < maxSize) {
                    IntStream.range(coreSize, maxSize).forEach(i -> newThread());
                }
                if (runnableQueue.size() == 0 && activeCount > coreSize) {
                    IntStream.range(coreSize, activeCount).forEach(i -> removeThread());
                }

            }
        }
    }

    @Override
    public void shutdown() {

    }

    //这一段方法不是特别重要,就有读者自己写
    @Override
    public int getInitSize() {
        return 0;
    }

    @Override
    public int getMaxSize() {
        return 0;
    }

    @Override
    public int getCoreSize() {
        return 0;
    }

    @Override
    public int getActiveCount() {
        return 0;
    }

    @Override
    public int getQueueSize() {
        return 0;
    }

    @Override
    public boolean isShutdown() {
        return this.isShutdown;
    }

    //把线程和internalTask一个组合
    private static class ThreadTask {
        public ThreadTask(Thread thread, InternalTask internalTask) {
            this.thread = thread;
            this.internalTask = internalTask;
        }

        Thread thread;
        InternalTask internalTask;
    }


}

线程池内部使用


//实现Runnable,用于线程池内部,该类会用到RunnableQueue,会不断的从队列中拿出线程并运行
public class InternalTask implements Runnable {

    private final RunnableQueue runnableQueue;
    private volatile boolean running = true;

    public InternalTask(RunnableQueue runnableQueue) {
        this.runnableQueue = runnableQueue;
    }

    @Override
    public void run() {
        //如果当前线程在运行中切没有被中断,则不断从缓存队列中拿出线程运行
        while (running && !Thread.currentThread().isInterrupted()) {
            try {
                Runnable task = runnableQueue.take();
                task.run();
            } catch (Exception e) {
                running = false;
                break;
            }
        }
    }

    //停止当前任务,会在shutdown中使用
    public void stop() {
        this.running = false;
    }
}

测试类

import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) {
        final ThreadPool threadPool = new BasicThreadPool(2, 6, 4, 100);
        for (int i = 0; i <= 20; i++) {
            threadPool.execute(() -> {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    System.out.println(Thread.currentThread().getName() + "开始了");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}

    4. 生产者-消费者模型:例如一个厨子10s生产一个,一个客人4s消费一个

    生产者-厨子

import java.util.concurrent.BlockingQueue;

public class Producer implements Runnable {
    public BlockingQueue<Integer> queue;

    public Producer(BlockingQueue queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(10000);
                queue.add(1);
                System.out.println("厨师放入了一个餐品");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

消费者-顾客

import java.util.concurrent.BlockingQueue;

public class Consumer implements Runnable {
    public BlockingQueue<Integer> queue;

    public Consumer(BlockingQueue queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(4000);
                queue.take();
                System.out.println("顾客消费了1个餐品");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

执行类

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class Main {
    public static void main(String[] args) {
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(100);
        Producer producer = new Producer(queue);
        Consumer consumer = new Consumer(queue);
        Thread threadA = new Thread(producer);
        Thread threadB = new Thread(consumer);
        threadA.start();
        threadB.start();
    }
}

    5. 单例模式:懒汉,饿汉,双重校验锁

    懒汉

public class Singleton {
    //私有构造方法
    private Singleton() {}

    //在成员位置创建该类的对象
    private static Singleton instance;

    //对外提供静态方法获取该对象
    public static Singleton getInstance() {

        if(instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

恶汉

public class Singleton {
    //私有构造方法
    private Singleton() {}

    //在成员位置创建该类的对象
    private static Singleton instance = new Singleton();

    //对外提供静态方法获取该对象
    public static Singleton getInstance() {
        return instance;
    }
}

双重校验锁

public class Singleton {

    //私有构造方法
    private Singleton() {}

    private static volatile Singleton instance;

   //对外提供静态方法获取该对象
    public static Singleton getInstance() {
        //第一次判断,如果instance不为null,不进入抢锁阶段,直接返回实际
        if(instance == null) {
            synchronized (Singleton.class) {
                //抢到锁之后再次判断是否为空
                if(instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

    6. 动态代理

    jdk动态代理

//卖票接口
public interface SellTickets {
    void sell();
}

//火车站  火车站具有卖票功能,所以需要实现SellTickets接口
public class TrainStation implements SellTickets {

    public void sell() {
        System.out.println("火车站卖票");
    }
}

//代理工厂,用来创建代理对象
public class ProxyFactory {

    private TrainStation station = new TrainStation();

    public SellTickets getProxyObject() {
        //使用Proxy获取代理对象
        /*
            newProxyInstance()方法参数说明:
                ClassLoader loader : 类加载器,用于加载代理类,使用真实对象的类加载器即可
                Class<?>[] interfaces : 真实对象所实现的接口,代理模式真实对象和代理对象实现相同的接口
                InvocationHandler h : 代理对象的调用处理程序
         */
        SellTickets sellTickets = (SellTickets) Proxy.newProxyInstance(station.getClass().getClassLoader(),
                station.getClass().getInterfaces(),
                new InvocationHandler() {
                    /*
                        InvocationHandler中invoke方法参数说明:
                            proxy : 代理对象
                            method : 对应于在代理对象上调用的接口方法的 Method 实例
                            args : 代理对象调用接口方法时传递的实际参数
                     */
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                        System.out.println("代理点收取一些服务费用(JDK动态代理方式)");
                        //执行真实对象
                        Object result = method.invoke(station, args);
                        return result;
                    }
                });
        return sellTickets;
    }
}

//测试类
public class Client {
    public static void main(String[] args) {
        //获取代理对象
        ProxyFactory factory = new ProxyFactory();
        
        SellTickets proxyObject = factory.getProxyObject();
        proxyObject.sell();
    }
}

    7. 手写一个HashMap,HashSet

    8. 有一个0-4的随机器rand4,如何实现0-6的随机器rand6,概率相同。拓展:rand X = func(rand Y),实现func函数

    9. 及其逆天的一个阿里手撕,来自于@byebyeneu:写三个Spring接口,调用第一个接口的时候返回这个接口的累计调用次数,调用第二个接口的时候返回调用这个接口的累计p99,调用第三个接口的时候,如果这个接口这时的qps<10,返回success,如果这个接口这时qps>10,返回err

全部评论
m
1 回复 分享
发布于 2024-12-29 14:12 河南
不是哥们,都26快手了,还在这写八股呢
1 回复 分享
发布于 2024-12-18 22:54 天津
收藏了佬
1 回复 分享
发布于 2024-12-11 18:49 山西
1 回复 分享
发布于 2024-12-11 15:12 山西
请问一下 第二题public volatile static Integer num = 0;这里volatile 不能保证多线程下的原子性吧?有影响吗
点赞 回复 分享
发布于 03-26 23:20 湖南
mark
点赞 回复 分享
发布于 03-16 11:17 广东
第八个的代码: import java.util.HashMap; import java.util.Map; import java.util.Random; /** 有一个1-4的随机器rand4,如何实现1-6的随机器rand6,概率相同。拓展:rand X = func(rand Y),实现func函数* */ public class RandMain { static Map<integer> map = new HashMap<>(); public static void main(String[] args) { map.put(1, 0); map.put(2, 0); map.put(3, 0); map.put(4, 0); map.put(5, 0); map.put(6, 0); for (int i = 0; i < 10000000; i++) { int rand = rand6(); map.put(rand, map.get(rand) + 1); } for(Map.Entry<integer> entry : map.entrySet()){ System.out.println(entry.getKey() + ":" + entry.getValue()); } } private static int rand6() { int num = (rand4() - 1) * 4 + rand4(); while(num > 6){ num = (rand4() - 1) * 4 + rand4(); } return num; } private static int rand4() { return new Random().nextInt(4) + 1; } } </integer></integer>
点赞 回复 分享
发布于 03-14 10:36 湖北
补充一个百度的,两个线程和队列模拟TCP三次握手
点赞 回复 分享
发布于 01-23 08:23 四川
别卷了别卷了
点赞 回复 分享
发布于 2024-12-11 22:09 广东
第八题是➗2再✖️三吗
点赞 回复 分享
发布于 2024-12-11 21:31 北京
接口怎么知道自己的响应时间,它自己能做全链路?
点赞 回复 分享
发布于 2024-12-11 16:41 广东
点赞 回复 分享
发布于 2024-12-11 15:36 四川

相关推荐

04-02 17:24
已编辑
沈阳工业大学 Java
一.基础内容-base:北京-部门以及业务:手机事业部,小米手机的相机开发-主要开发语言:java-时间:2024.10.09-时长:70min二.内容面试官很严谨确认一下岗位信息自我介绍介绍做过项目中最有亮点的,(介绍一个旅游险业务的实习项目,介绍一下自我项目的算法优化)异步并发时,如何保证多线程访问的数据一致性-加CAS都有哪些实现锁的处理:syn、lock、CAS锁升级过程讲一讲CAS一定有自旋吗?CAS底层如何实现的?具体到操作系统层面是怎么回事?你刚才提到unsafe,那unsafe在硬件角度来说,是不是原子操作,如果是,都有啥功能?动态代理和静态代理区别动态代理都如何实现的?JDK实现方式和cglib这两种方式实现代理的过程中,效率谁更高一点?linux命令vim文件时如何快速查找字符串(忘记了)http和https的区别(感谢面试官没疯狂问我底层的东西)https的加密过程详细说一下?你说这么多,你认为https加密过程是非中心对称还是中心对称?哪你认为非中心对称和中心对称分别如何在https中实现的?那你说一下http三次握手、http四次挥手?为什么是三次握手,两次不行吗?请求超时怎么办?四次挥手的时候,为什么要发两次fin请求,一次不行吗?你了解过为什么客户端关闭要等2msl吗?(这我真不知道,他难为鼠鼠了,我就说硬性规定吧)http的状态码都有哪些?(估计看我不会了,问点简单的)400是什么意思-表示服务器无法理解客户端发送的请求你了解树这种数据结构吗?都有哪些树你提到红黑树和平衡树,我问你,两者有什么区别,如果你在不同应用环境下,如何对两者进行选择?树的遍历方式arrayList的扩容机制arrayList是线程安全的吗?会存在什么问题?如何解决这个问题?COW是什么东西?如何实现的?用过哪些设计模式三.手撕(10min)生成括号(回溯mid)(AK)反问:1.流程:三次面试,本次第一轮技术面2.表现:没啥问题,基本功扎实,算法做的也可以,说有很多候选人,会最后排个名次。最终:通过==============欢迎大家关注鼠鼠,鼠鼠会陆续发一下面经(都是真实发生的)、一些学习经验、以及通过生动、巧妙的方式,去更好的理解难记住、易忘的知识!#小米##双非应该如何逆袭?##双非有机会进大厂吗#
点赞 评论 收藏
分享
头像 会员标识
03-21 10:54
已编辑
门头沟学院 后端
分享面经,攒攒好运部门:核心本地商业-业务研发平台40min项目和八股问答+手撕自我介绍一下项目中这些技术栈都是用来做什么的,展开讲讲为什么使用spring&nbsp;cloudspring&nbsp;cloud和消息队列的区别spring&nbsp;boot中使用到了哪些设计模式spring中,某一个类中普通方法A调用同一个类中的事务方法B,这个事务还会生效吗?mybatis如何防止SQL注入如何合理设计项目的数据表的,有哪些考虑为什么使用Redis,直接将数据放入数据库中不行吗使用布隆过滤器解决缓存穿透问题,具体展开说说刚才说到布隆过滤器的误判,展开说说Java内存模型了解吗你们mysql的存储引擎使用的哪个Git使用过哪些命令Redis的持久化机制了解吗线程池使用过吗,他的核心参数有哪些,如何设置这些参数的,考虑到哪些因素拒绝策略有哪些,默认的是什么具体说说如何使用&nbsp;Redis&nbsp;进行缓存预热的数据库的索引如何验证是否有效呢Explain中的extra&nbsp;info中的Using&nbsp;filesort知道吗(听过但具体的没说上来)java平时用的是哪个版本Java1.8的一些新特性了解吗,展开说说【顺序不一定是这样,回忆可能错乱】手撕&nbsp;力扣原题:删除链表中倒数第N个节点几分钟做完,然后让我讲讲怎么做的,分析一下时间复杂度和空间复杂度反问:部门主要是做什么的(闪送)平常工作中使用到哪些技术栈-------------------------------整体感觉有几个问题回答的一般,目前状态还是业务初试,希望能过更新,早上约了当天下午二面
查看24道真题和解析
点赞 评论 收藏
分享
评论
63
372
分享

创作者周榜

更多
牛客网
牛客企业服务