面试手撕-多线程&死锁

发布于:2025-02-10 ⋅ 阅读:(27) ⋅ 点赞:(0)

使用多线程的方式

继承 Thread

实现 Runnable 接口

实现 Callable 接口

  • FutureTask
  • CompletableFuture

使用 线程池

public class ArraySum {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // 初始化一个长度为1000的数组
        int[] array = new int[100];
        for (int i = 0; i < array.length; i++) {
            array[i] = i + 1;  // 数组元素为1到100
        }

        // 创建线程池,最多使用10个线程
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        // 每个线程计算的部分长度
        int chunkSize = array.length / 10;

        // 使用一个 AtomicInteger 来确保线程安全的累加
        AtomicInteger totalSum = new AtomicInteger(0);

        // 创建任务并提交给线程池
        for (int i = 0; i < 10; i++) {
            final int start = i * chunkSize;
            final int end = (i + 1) * chunkSize;
            executorService.submit(() -> {
                int partialSum = 0;
                for (int j = start; j < end; j++) {
                    partialSum += array[j];
                }
                // 通过 AtomicInteger 将部分和添加到总和
                totalSum.addAndGet(partialSum);
            });
        }

        // 等待所有线程执行完毕
        executorService.shutdown();

        // 打印最终结果
        System.out.println("Total Sum: " + totalSum.get());
    }
}

用Java写一段死锁的代码

死锁
● 预防死锁
● 避免死锁
● 检测死锁
● 解除死锁

public class Deadlock {

    // 资源A和资源B
    private static final Object resourceA = new Object();
    private static final Object resourceB = new Object();

    public static void main(String[] args) {
        // 创建线程1,试图先获取资源A再获取资源B
        Thread thread1 = new Thread(() -> {
            synchronized (resourceA) {
                System.out.println("Thread 1: Locked resource A");

                // 模拟一些工作
                try { Thread.sleep(100); } catch (InterruptedException e) {}

                synchronized (resourceB) {
                    System.out.println("Thread 1: Locked resource B");
                }
            }
        });

        // 创建线程2,试图先获取资源B再获取资源A
        Thread thread2 = new Thread(() -> {
            synchronized (resourceB) {
                System.out.println("Thread 2: Locked resource B");

                // 模拟一些工作
                try { Thread.sleep(100); } catch (InterruptedException e) {}

                synchronized (resourceA) {
                    System.out.println("Thread 2: Locked resource A");
                }
            }
        });

        // 启动线程
        thread1.start();
        thread2.start();
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到