创建线程的5种方式

1. 继承 Thread

  • 原理
    • 通过继承 Thread 类并重写 run() 方法来定义线程任务。
  • 步骤
    1. 创建一个继承 Thread 的子类。
    2. 重写 run() 方法,定义线程执行的任务。
    3. 创建子类实例并调用 start() 方法启动线程。
  • 示例
class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("线程运行中: " + Thread.currentThread().getName());
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start(); 
    }
}
  • 特点
    • 简单直接。
    • 占用继承机会。
2. 实现 Runnable 接口
  • 原理
    • 通过实现 Runnable 接口并重写 run() 方法来定义线程任务,然后将 Runnable 实例传递给 Thread 对象.
  • 步骤
    1. 创建一个实现 Runnable 接口的类。
    2. 重写 run() 方法,定义线程执行的任务.
    3. 创建 Thread 对象并传入 Runnable 实例.
    4. 调用 start() 方法启动线程.
  • 示例
class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("线程运行中: " + Thread.currentThread().getName());
    }
}

public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyRunnable());
        thread.start(); 
    }
}
  • 特点
    • 更灵活,适合多线程共享资源的场景.
    • 避免了单继承的限制.
3. 使用 CallableFuture
  • 原理
    • 通过实现 Callable 接口定义线程任务,Callablecall() 方法可以返回结果并抛出异常。结合 FutureFutureTask 可以获取线程的执行结果.
  • 步骤
    1. 创建一个实现 Callable 接口的类.
    2. 重写 call() 方法,定义线程执行的任务并返回结果.
    3. 创建 FutureTask 对象并传入 Callable 实例.
    4. 创建 Thread 对象并传入 FutureTask 实例.
    5. 调用 start() 方法启动线程.
    6. 通过 FutureTask.get() 获取线程执行结果.
  • 示例
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

class MyCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        return "线程运行结果: " + Thread.currentThread().getName();
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        FutureTask<String> futureTask = new FutureTask<>(new MyCallable());
        Thread thread = new Thread(futureTask);
        thread.start(); 
        System.out.println(futureTask.get()); 
    }
}
  • 特点
    • 支持返回值.
    • 支持异常抛出.
    • 适用于需要获取线程执行结果的场景.
4. 使用线程池(ExecutorService
  • 原理
    • 通过线程池管理线程的创建和销毁,避免频繁创建和销毁线程的开销.
  • 步骤
    1. 使用 Executors 工具类创建线程池.
    2. 提交 RunnableCallable 任务给线程池.
    3. 线程池自动管理线程的执行.
  • 示例
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2); 
        
        executor.submit(() -> {
            System.out.println("线程运行中: " + Thread.currentThread().getName());
        });

        executor.submit(() -> {
            return "线程运行结果: " + Thread.currentThread().getName();
        });

        executor.shutdown(); 
    }
}
  • 特点
    • 高效管理线程资源.
    • 支持 RunnableCallable 任务.
    • 适用于需要管理多个线程的场景.
5. 使用 CompletableFuture(Java 8+)
  • 原理
    • CompletableFutureFuture 的增强版,支持异步编程和链式调用.
  • 步骤
    1. 使用 CompletableFuture.runAsync()supplyAsync() 提交任务.
    2. 通过回调方法处理任务结果.
  • 示例
import java.util.concurrent.CompletableFuture;

public class Main {
    public static void main(String[] args) {
        CompletableFuture.runAsync(() -> {
            System.out.println("线程运行中: " + Thread.currentThread().getName());
        });

        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            return "线程运行结果: " + Thread.currentThread().getName();
        });

        future.thenAccept(result -> System.out.println(result)); 
    }
}
  • 特点
    • 支持异步编程.
    • 支持链式调用和组合任务.
    • 适用于复杂的异步任务场景.
创建方式优点缺点适用场景
继承 Thread简单直接占用继承机会简单任务
实现 Runnable灵活,避免单继承限制无返回值多线程共享资源
使用 Callable支持返回值和异常需要结合 Future 使用需要获取线程结果
使用线程池高效管理线程资源需要手动关闭线程池多任务并发执行
使用 CompletableFuture支持异步编程和链式调用需要 Java 8+复杂异步任务
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值