【Java多线程】2 Java中的线程创建


第二部分:Java 中的线程创建


一、Java 中的线程创建

在 Java 中,我们可以通过以下三种方式来创建线程:继承 Thread 类、实现 Runnable 接口、使用 CallableFuture。每种方式各有特点,适合不同的应用场景。


二、使用 Thread 类创建线程

Thread 是 Java 提供的基础线程类,直接继承它并重写 run() 方法即可创建线程。

步骤:

  1. 定义一个类继承 Thread
  2. 重写 run() 方法,将线程执行的任务放入 run() 中。
  3. 创建该类的实例,并调用 start() 方法启动线程。

示例代码:

class MyThread extends Thread {
    @Override
    public void run() {
        // 线程的任务代码
        System.out.println("你好,来自 MyThread!当前线程:" + Thread.currentThread().getName());
    }
}

public class ThreadExample {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();  // 启动线程,自动调用 run() 方法
    }
}

说明

  • start() 方法会启动新线程并调用 run() 方法。如果直接调用 run() 而不使用 start(),任务将在当前线程中运行,而不会启动新线程。

三、使用 Runnable 接口创建线程

相比继承 Thread,实现 Runnable 接口更灵活,因为 Java 是单继承,直接继承 Thread 限制了类的扩展性。Runnable 更适合需要继承其他类的情况下使用。

步骤:

  1. 创建一个类实现 Runnable 接口。
  2. 重写 run() 方法。
  3. 使用 Thread 构造函数创建一个新线程,并传入 Runnable 实例。
  4. 调用 start() 方法启动线程。

示例代码:

class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("你好,来自 MyRunnable!当前线程:" + Thread.currentThread().getName());
    }
}

public class RunnableExample {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);  // 传入 Runnable 实例
        thread.start();  // 启动线程
    }
}

四、使用 CallableFuture 创建线程

Runnable 接口的 run() 方法没有返回值,无法抛出异常。如果需要在线程执行后获取结果或处理异常,可以使用 CallableFuture

步骤:

  1. 实现 Callable 接口,并重写 call() 方法。call() 可以返回结果并抛出异常。
  2. 使用 ExecutorService 提交 Callable 任务,得到一个 Future 对象。
  3. 通过 Future.get() 方法获取任务结果。

示例代码:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

class MyCallable implements Callable<String> {
    @Override
    public String call() {
        return "你好,来自 MyCallable!";
    }
}

public class CallableExample {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<String> future = executor.submit(new MyCallable());

        try {
            String result = future.get();  // 获取任务结果
            System.out.println(result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
        }
    }
}

五、选择合适的方式

  • 继承 Thread:适合简单任务,但因为单继承限制,不够灵活。
  • 实现 Runnable:更灵活,适合多数场景,尤其是需要复用线程代码的情况。
  • 使用 CallableFuture:适合需要线程返回结果或抛出异常的场景。

总结

Java 提供了三种不同的线程创建方式,每种方式适用于不同的开发需求。下一步,我们将学习 线程的生命周期和状态,深入了解线程在不同阶段的状态变化和常用的控制方法。掌握了这些方法,让你从容应对多线程编程的复杂性。

点我跳转下一课^_^

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天呐少爷

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值