news 2026/4/16 17:45:25

Java 面试:10 个手写代码题(单例、排序、线程池等)

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Java 面试:10 个手写代码题(单例、排序、线程池等)

以下是10个Java面试常见手写代码题的实现,涵盖单例模式、排序算法、线程池等核心知识点:

单例模式(双重校验锁)

public class Singleton { private volatile static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }

快速排序

public void quickSort(int[] arr, int low, int high) { if (low < high) { int pivot = partition(arr, low, high); quickSort(arr, low, pivot - 1); quickSort(arr, pivot + 1, high); } } private int partition(int[] arr, int low, int high) { int pivot = arr[high]; int i = low - 1; for (int j = low; j < high; j++) { if (arr[j] < pivot) { i++; swap(arr, i, j); } } swap(arr, i + 1, high); return i + 1; } private void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }

线程池实现

public class CustomThreadPool { private final BlockingQueue<Runnable> taskQueue; private final List<WorkerThread> workers; public CustomThreadPool(int poolSize) { this.taskQueue = new LinkedBlockingQueue<>(); this.workers = new ArrayList<>(); for (int i = 0; i < poolSize; i++) { WorkerThread worker = new WorkerThread(); worker.start(); workers.add(worker); } } public void execute(Runnable task) { taskQueue.offer(task); } private class WorkerThread extends Thread { public void run() { while (true) { try { Runnable task = taskQueue.take(); task.run(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } } }

生产者消费者模式

public class ProducerConsumer { private final Queue<Integer> queue = new LinkedList<>(); private final int capacity; public ProducerConsumer(int capacity) { this.capacity = capacity; } public void produce() throws InterruptedException { int value = 0; while (true) { synchronized (this) { while (queue.size() == capacity) { wait(); } queue.add(value++); notifyAll(); Thread.sleep(1000); } } } public void consume() throws InterruptedException { while (true) { synchronized (this) { while (queue.isEmpty()) { wait(); } int value = queue.poll(); notifyAll(); Thread.sleep(1000); } } } }

二分查找

public int binarySearch(int[] arr, int target) { int left = 0, right = arr.length - 1; while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == target) { return mid; } else if (arr[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return -1; }

反转链表

public ListNode reverseList(ListNode head) { ListNode prev = null; ListNode curr = head; while (curr != null) { ListNode nextTemp = curr.next; curr.next = prev; prev = curr; curr = nextTemp; } return prev; }

LRU缓存实现

class LRUCache { class Node { int key, value; Node prev, next; Node(int key, int value) { this.key = key; this.value = value; } } private Map<Integer, Node> cache; private int capacity; private Node head, tail; public LRUCache(int capacity) { this.capacity = capacity; cache = new HashMap<>(); head = new Node(0, 0); tail = new Node(0, 0); head.next = tail; tail.prev = head; } public int get(int key) { if (!cache.containsKey(key)) return -1; Node node = cache.get(key); remove(node); add(node); return node.value; } public void put(int key, int value) { if (cache.containsKey(key)) { remove(cache.get(key)); } Node node = new Node(key, value); cache.put(key, node); add(node); if (cache.size() > capacity) { Node toRemove = tail.prev; remove(toRemove); cache.remove(toRemove.key); } } private void add(Node node) { Node next = head.next; head.next = node; node.prev = head; node.next = next; next.prev = node; } private void remove(Node node) { Node prev = node.prev; Node next = node.next; prev.next = next; next.prev = prev; } }

二叉树层序遍历

public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); if (root == null) return result; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { int levelSize = queue.size(); List<Integer> currentLevel = new ArrayList<>(); for (int i = 0; i < levelSize; i++) { TreeNode node = queue.poll(); currentLevel.add(node.val); if (node.left != null) queue.offer(node.left); if (node.right != null) queue.offer(node.right); } result.add(currentLevel); } return result; }

字符串转整数(atoi)

public int myAtoi(String s) { if (s == null || s.isEmpty()) return 0; int index = 0, sign = 1, total = 0; // 跳过空格 while (index < s.length() && s.charAt(index) == ' ') { index++; } // 处理符号 if (index < s.length() && (s.charAt(index) == '+' || s.charAt(index) == '-')) { sign = s.charAt(index) == '+' ? 1 : -1; index++; } // 转换数字 while (index < s.length()) { int digit = s.charAt(index) - '0'; if (digit < 0 || digit > 9) break; // 检查溢出 if (Integer.MAX_VALUE / 10 < total || (Integer.MAX_VALUE / 10 == total && Integer.MAX_VALUE % 10 < digit)) { return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; } total = 10 * total + digit; index++; } return total * sign; }

实现阻塞队列

public class BlockingQueue<T> { private Queue<T> queue = new LinkedList<>(); private int capacity; private Lock lock = new ReentrantLock(); private Condition notFull = lock.newCondition(); private Condition notEmpty = lock.newCondition(); public BlockingQueue(int capacity) { this.capacity = capacity; } public void put(T element) throws InterruptedException { lock.lock(); try { while (queue.size() == capacity) { notFull.await(); } queue.add(element); notEmpty.signal(); } finally { lock.unlock(); } } public T take() throws InterruptedException { lock.lock(); try { while (queue.isEmpty()) { notEmpty.await(); } T item = queue.remove(); notFull.signal(); return item; } finally { lock.unlock(); } } }
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/16 11:00:33

亚里士多德与集体好奇心

亚里士多德与集体好奇心 关键词:亚里士多德、集体好奇心、哲学思想、知识探索、社会认知 摘要:本文旨在探讨亚里士多德的哲学思想与集体好奇心之间的联系。通过深入研究亚里士多德的核心理论,分析集体好奇心在知识探索和社会认知发展中的作用。文章将从亚里士多德的思想背景…

作者头像 李华
网站建设 2026/4/16 9:18:17

揭秘8款免费AI论文工具:真实参考文献+8%AIGC率,瑞达写作藏高阶玩法

90%的学生都不知道&#xff0c;真正的AI论文工具不只是帮你“写”&#xff0c;而是帮你“赢”。当别人还在为降重和AI检测率焦头烂额时&#xff0c;少数人已经用上了能自动生成真实参考文献、并将AIGC率精准控制在8%以下的“黑科技”。 引言&#xff1a;当“写论文”变成一场信…

作者头像 李华
网站建设 2026/4/16 10:55:12

【阿里AI大赛】-二手车价格预测使用五折交叉验证

使用五折交叉验证&#xff08;5-Fold Cross Validation&#xff09;可以帮助降低MAE&#xff08;平均绝对误差&#xff09;&#xff0c;但需要结合合理的模型调优策略。以下是具体分析&#xff1a; 五折交叉验证的作用原理 五折交叉验证将数据集分为5个等份&#xff0c;每次用其…

作者头像 李华
网站建设 2026/4/16 11:11:57

Tauri框架实战——托盘左键不显示菜单

背景 近期&#xff0c;我基于自研的个人时间管理 Web 应用 「时光助手」&#xff0c;借助 AI 辅助开发&#xff0c;通过 Tauri 框架完成了 Windows 客户端的打包工作。初次体验 Tauri 便收获了不错的反馈 —— 其生成的客户端体积轻量化、运行性能优异&#xff0c;且与 Web 端…

作者头像 李华
网站建设 2026/4/16 12:44:01

CES 2026(2026国际消费电子展)智能穿戴设备趋势与亮点 的研究报告

2026 CES 智能穿戴设备研究报告 福布斯The Verge凤凰网科技qianjia.com动点科技商业电讯 一、展会概况与定义 CES 2026 于 2026 年 1 月 在美国拉斯维加斯举办&#xff0c;作为全球最大科技展之一&#xff0c;它聚焦最新消费电子与人工智能创新。本届展会特别强调 AI 感知交…

作者头像 李华
网站建设 2026/4/15 21:04:36

深入浅出大数据基石:Hadoop 生态核心技术全解析

在数字化浪潮席卷全球的今天&#xff0c;大数据已成为企业核心竞争力的关键。Hadoop 作为大数据处理的经典框架&#xff0c;凭借其高可靠性、高扩展性和高容错性&#xff0c;成为处理海量数据的事实标准。本文将从基础认知到实操落地&#xff0c;全面拆解 Hadoop 生态核心技术&…

作者头像 李华