全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-10 8 分钟 ✍️ juanwangdev

程的创建与启动

Java 提供三种创建线程的方式,各有特点和适用场景。

方式一:继承 Thread 类

Java
public class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("线程执行:" + Thread.currentThread().getName());
    }
}

// 使用
MyThread thread = new MyThread();
thread.start();  // 启动线程

注意:调用 start() 方法启动线程,不是 run()。start() 创建新线程执行 run(),直接调用 run() 只是普通方法调用。

方式二:实现 Runnable 接口

Java
public class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("线程执行");
    }
}

// 使用
Thread thread = new Thread(new MyRunnable());
thread.start();

// Lambda 简化(Java 8+)
Thread thread = new Thread(() -> {
    System.out.println("线程执行");
});
thread.start();

Runnable vs Thread

特性RunnableThread
灵活性可继承其他类不能继承其他类
资源共享同一 Runnable 可多线程共享不易共享
推荐✅ 推荐一般场景

方式三:实现 Callable 接口

Callable 可返回结果和抛出异常:

Java
public class MyCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        Thread.sleep(1000);
        return "执行结果";
    }
}

// 使用 FutureTask 包装
FutureTask<String> futureTask = new FutureTask<>(new MyCallable());
Thread thread = new Thread(futureTask);
thread.start();

// 获取结果(阻塞等待)
String result = futureTask.get();  // 等待线程完成
System.out.println(result);

// 带超时获取
String result = futureTask.get(3, TimeUnit.SECONDS);  // 超时抛异常

Callable vs Runnable

特性CallableRunnable
返回结果✅ 有返回值❌ 无返回值
异常处理✅ 可抛异常❌ 不能抛 checked 异常
使用方式FutureTask 包装直接传入 Thread

Thread 常用方法

Java
Thread thread = new Thread(() -> {
    // 线程任务
});

thread.start();              // 启动线程
thread.getName();            // 获取线程名
thread.setName("myThread");  // 设置线程名
thread.getId();              // 获取线程 ID
thread.isAlive();            // 是否存活
thread.join();               // 等待线程结束
thread.join(1000);           // 等待最多 1 秒
thread.interrupt();          // 中断线程
Thread.currentThread();      // 获取当前线程
Thread.sleep(1000);          // 线程休眠 1 秒(静态方法)

线程命名与获取

Java
// 创建时命名
Thread thread = new Thread(runnable, "worker-thread");

// 运行中获取当前线程
Thread current = Thread.currentThread();
String name = current.getName();

程示例:多线程执行任务

Java
public class ThreadDemo {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + " 执行");
            }, "thread-" + i);
            thread.start();
        }
    }
}

// 输出顺序不确定(并发执行)
// thread-0 执行
// thread-2 执行
// thread-1 执行
// ...

要点总结

  • 创建方式:继承 Thread、实现 Runnable、实现 Callable
  • Runnable 推荐使用,更灵活,可共享资源
  • Callable 有返回值,配合 FutureTask 使用
  • start() 启动线程,run() 只是普通方法调用
  • Thread.sleep() 休眠当前线程(静态方法)
  • thread.join() 等待线程结束
  • Thread.currentThread() 获取当前线程对象

📝 发现内容有误?点击此处直接编辑

← 上一篇 程池
下一篇 → 程的生命周期
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库