Java创建多线程方式

继承 Thread 类

public class Test extends Thread {
    @Override
    public void run() {
        System.out.println("current thread is:" + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        Test test = new Test();
        test.start();//启动线程
    }
}

实现 Runnable 接口

在这里插入图片描述
方式1:

public class Test implements Runnable {
    @Override
    public void run() {
        System.out.println("current thread is:" + Thread.currentThread().getName());
    }

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

方式2:
参数 new Runnable() { … } 是一个匿名内部类实现 Runnable 接口。【传参,new一个接口,需要实现该接口的方法】

public class Test{
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("current thread is:"+Thread.currentThread().getName());
            }
        });
        thread.start();
    }
}

方式3:
只有一个抽象方法的接口被称为函数式接口。函数式接口可以用于 Lambda 表达式
在这里插入图片描述

public class Test {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("current thread is:" + Thread.currentThread().getName());
        });
        thread.start();
    }
}

实现 Callable 接口

public class Test implements Callable<String> { // 和Runnable这个有返回值
    @Override
    public String call() throws Exception {
        System.out.println("current thread is:" + Thread.currentThread().getName());
        return "yes";
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Test test = new Test();
        // FutureTask用来包装Callable的实例
        FutureTask<String> futureTask = new FutureTask<>(test);
        Thread thread = new Thread(futureTask);
        thread.start();
        System.out.println(futureTask.get()); // 返回值
    }
}

Thread 不支持直接运行 Callable

Thread 类本身只接受 Runnable 对象作为参数来创建线程,而 Runnable 不返回任何结果。这意味着如果你想要使用 Callable,必须将其转换为 Runnable 才能与 Thread 一起使用。

FutureTask 的作用

FutureTask 是 Java 提供的一个可以同时充当 RunnableFuture 的类:

  • 它实现了 Runnable 接口,所以可以作为一个任务提交给 Thread 来执行。
  • 它也实现了 Future 接口,允许获取任务执行的结果。

在这里插入图片描述

具体的作用:

  1. 包装 CallableFutureTask 可以接受一个 Callable 对象并将其转换为 Runnable。这样可以把 Callable 任务提交给线程执行。
  2. 获取执行结果:通过 FutureTask,可以使用 get() 方法在任务执行完成后获取 Callable 返回的结果。get()阻塞直到任务执行完成。
  3. 处理异常FutureTask 也可以捕获并处理 Callable 中抛出的异常。

线程池

在工作中,使用线程池是更为推荐的方法,因为它能更好地管理和复用线程资源,避免频繁创建和销毁线程带来的开销。

@Slf4j
@Configuration
public class testConfig {

    @Bean
    public Executor testExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 1.核心线程池大小
        executor.setCorePoolSize(4);
        // 2.最大线程池大小
        executor.setMaxPoolSize(8);
        // 3.队列大小
        executor.setQueueCapacity(999);
        // 4.线程名称前缀
        executor.setThreadNamePrefix("test-executor-");
        // 5.拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        executor.initialize();
        return executor;
    }
}

拒绝策略 :

  • 当任务队列已满且线程数已达到最大值时,新任务会被拒绝。常用的拒绝策略有:
    • AbortPolicy:直接抛出 RejectedExecutionException
    • CallerRunsPolicy:由调用线程(提交任务的线程)处理该任务。
    • DiscardPolicy:直接丢弃任务,不抛出异常。
    • DiscardOldestPolicy:丢弃队列中最老的任务,然后重新尝试提交新任务。

❤觉得有用的可以留个关注~~❤

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值