线程基础面试题

一、Java 实现线程的核心方法(基础知识点)

Java 中创建线程有 3 种标准方式(从基础到进阶),核心是围绕 Thread 类和 Runnable/Callable 接口展开:

image

  1. 方式 1:继承 Thread 类(基础)
// 步骤1:继承Thread类,重写run()方法
class MyThread extends Thread {
    @Override
    public void run() {
        // 线程执行的业务逻辑
        for (int i = 0; i < 5; i++) {
            System.out.println("继承Thread:" + i + ",线程名:" + Thread.currentThread().getName());
        }
    }
}

// 步骤2:创建线程对象并启动(必须调用start(),而非直接调用run())
public class ThreadExtendDemo {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.setName("自定义线程");
        thread.start(); // 启动线程(JVM会调用run()方法)
        // thread.run(); // 错误:直接调用run()是普通方法执行,不会创建新线程
    }
}

方式 2:实现 Runnable 接口(推荐)


// 步骤1:实现Runnable接口,重写run()方法
class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("实现Runnable:" + i + ",线程名:" + Thread.currentThread().getName());
        }
    }
}

// 步骤2:将Runnable实例传入Thread,启动线程
public class RunnableImplDemo {
    public static void main(String[] args) {
        MyRunnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable, "Runnable线程");
        thread.start();

        // 简化写法:匿名内部类
        new Thread(() -> {
            System.out.println("匿名Runnable:" + Thread.currentThread().getName());
        }, "匿名线程").start();
    }
}

方式 3:实现 Callable 接口(带返回值)


import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

// 步骤1:实现Callable接口,重写call()方法(有返回值、可抛异常)
class MyCallable implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            sum += i;
        }
        return sum; // 返回计算结果
    }
}

// 步骤2:通过FutureTask包装Callable,传入Thread启动
public class CallableImplDemo {
    public static void main(String[] args) throws Exception {
        MyCallable callable = new MyCallable();
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        Thread thread = new Thread(futureTask, "Callable线程");
        thread.start();

        // 获取返回值(get()会阻塞,直到线程执行完成)
        Integer result = futureTask.get();
        System.out.println("1-100求和结果:" + result); // 输出:5050
    }
}

面试高频题:start() 和 run() 方法的区别

image

public class StartVsRunDemo {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("线程执行:" + Thread.currentThread().getName());
        });

        // 1. 调用run():主线程执行(名称为main)
        thread.run(); // 输出:线程执行:main

        // 2. 调用start():新线程执行(名称为Thread-0)
        thread.start(); // 输出:线程执行:Thread-0

        // 3. 多次调用start():抛异常
        // thread.start(); // 抛出IllegalThreadStateException
    }
}

为什么实现 Runnable 接口比继承 Thread 类更好

image

面试高频题:Java 线程的 6 种状态

image

image

image

posted @ 2026-03-11 11:31  白鹿为溪  阅读(15)  评论(0)    收藏  举报