创建线程的5种方式

1.实现runable接口,实现run方法
2.继承thread类,实现run方法
3.实现Callable接口。实现Call方法,Call方法有返回值和异常
4.使用线程池
5.使用completableFuture

以下是每种创建线程方式的简单示例:

1. 实现Runnable接口,实现run方法

public class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("Thread running using Runnable interface: " + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        Thread thread = new Thread(new MyRunnable());
        thread.start();
    }
}

2. 继承Thread类,实现run方法

public class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("Thread running by extending Thread class: " + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}

3. 实现Callable接口,实现call方法(有返回值和异常)

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

public class MyCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        return "Result from Callable: " + Thread.currentThread().getName();
    }

    public static void main(String[] args) {
        MyCallable callable = new MyCallable();
        FutureTask<String> futureTask = new FutureTask<>(callable);
        Thread thread = new Thread(futureTask);
        thread.start();

        try {
            // 获取Callable的结果
            String result = futureTask.get();
            System.out.println(result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}

4. 使用线程池

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolExample {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        Runnable task1 = () -> System.out.println("Task 1 running in thread pool: " + Thread.currentThread().getName());
        Runnable task2 = () -> System.out.println("Task 2 running in thread pool: " + Thread.currentThread().getName());

        executorService.submit(task1);
        executorService.submit(task2);

        // 关闭线程池
        executorService.shutdown();
    }
}

5. 使用CompletableFuture

import java.util.concurrent.CompletableFuture;

public class CompletableFutureExample {
    public static void main(String[] args) {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                // 模拟耗时操作
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Result from CompletableFuture: " + Thread.currentThread().getName();
        });

        // 添加回调方法,当future完成时执行
        future.thenAccept(result -> {
            System.out.println(result);
        });

        // 主线程可以继续执行其他任务,而不需要等待future完成
        System.out.println("Main thread continues to execute...");

        // 为了演示,这里让主线程等待一段时间,以便观察CompletableFuture的结果
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

2.CompletableFuture.supplyAsync 和 CompletableFuture.runAsync 区别

CompletableFuture.supplyAsyncCompletableFuture.runAsync 都是 Java 中 CompletableFuture 类提供的用于启动异步任务的方法,但它们之间存在一些关键的区别。

主要区别

  1. 返回值

    • CompletableFuture.supplyAsync:用于执行一个可以返回结果的异步计算。它返回一个 CompletableFuture<T> 对象,其中 T 是通过任务计算得到的结果类型。
    • CompletableFuture.runAsync:用于执行一个不需要返回结果的异步任务。它返回一个 CompletableFuture<Void> 对象,仅表示任务的完成状态。
  2. 适用场景

    • CompletableFuture.supplyAsync:适用于需要执行一个计算并希望得到结果的场景。例如,从数据库中查询数据、执行复杂的计算等。
    • CompletableFuture.runAsync:适用于只需执行某些操作而不需要计算返回值的场景。例如,发送通知、记录日志、执行 I/O 操作等。

示例代码

CompletableFuture.supplyAsync 示例

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    // 模拟一些计算
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    return "Hello, World!";
});

// 获取异步任务的结果
String result = future.join(); // 或者使用 future.get(),但 join() 更常用,因为它不会抛出 InterruptedException
System.out.println(result);

CompletableFuture.runAsync 示例

CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
    // 模拟一些操作
    for (int i = 0; i < 10; i++) {
        System.out.println("Running task: " + i);
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
});

// 等待异步任务执行完成
future.join(); // 或者使用 future.get(),但在这里 join() 更合适,因为它表示等待任务完成

总结

  • 使用 CompletableFuture.supplyAsync 当你需要执行一个计算并希望得到结果时。
  • 使用 CompletableFuture.runAsync 当你只想执行一个操作而不需要返回值时。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值