java实现多线程的四种方式

文章展示了Java中实现多线程的四种常见方式:继承Thread类、实现Runnable接口、实现Callable接口以及使用线程池。提供了相应的代码示例,包括使用SpringBoot的ThreadPoolTaskExecutor配置线程池,并通过ExecutorService执行任务。此外,文章还提到了注解@SneakyThrows的用法以及Executor与Executors的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、实现多线程的方式

1、继承Thread类

2、实现Runnable接口

3、实现Callable接口(JDK>=1.5)

4、线程池方式创建

二、代码示例

package com.example.demo5;

import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.util.concurrent.*;

/**
 * @Author lcb
 * @Date 2023/03/13
 **/
@SpringBootTest
public class ThreadTest {

    /**
     * 实现多线程的方式:
     * 1、继承Thread类
     * 2、实现Runnable接口
     * 3、实现Callable接口(JDK>=1.5)
     * 4、线程池方式创建
     * <p>
     * 相关说明:
     * 1、@SneakyThrows详见:https://blog.csdn.net/m290345792/article/details/125510133
     * 2、Executor与Executors的区别见:https://www.cnblogs.com/hujinshui/p/10367876.html
     * 3、Executors五种线程池的对比与使用见:https://www.jianshu.com/p/135c89001b61
     */
    @Resource
    private ThreadPoolConfig threadPool;

    @Test

    @SneakyThrows
    void test() {
        //1、继承Thread类
        System.out.println("==1、继承Thread类start==");
        Thread thread1 = new Thread(new ThreadDemo("继承thread类"));
        thread1.start();
        Thread.sleep(10);
        System.out.println("==1、继承Thread类end==\n");

        //2、实现Runnable接口
        System.out.println("==2、实现Runnable接口start==");
        Thread thread2 = new Thread(new RunnableDemo("实现Runnable接口"));
        thread2.start();
        Thread.sleep(10);
        System.out.println("==2、实现Runnable接口end==\n");

        //3、实现Callable接口
        System.out.println("==3、实现Callable接口start==");
        FutureTask<String> callable = new FutureTask<>(new CallableDemo("callable线程1"));
        callable.run();
        System.out.println(callable.get());
        Thread.sleep(10);
        System.out.println("==3、实现Callable接口end==\n");

        //4、线程池方式创建
        //1)
        System.out.println("==4、线程池方式创建1 start==");
        Executor executor = threadPool.taskExecutor();
        executor.execute(new ThreadDemo("继承thread类"));
        executor.execute(new RunnableDemo("实现Runnable接口"));
        Thread.sleep(10);
        System.out.println("==4、线程池方式创建1 end==\n");

        //2)
        System.out.println("==4、线程池方式创建2 start==");
        ExecutorService executorService = Executors.newCachedThreadPool((ThreadFactory) executor);
        executorService.execute(new ThreadDemo("继承thread类"));
        executorService.execute(new RunnableDemo("实现Runnable接口"));
        Future<String> callable2 = executorService.submit(new CallableDemo("callable线程2"));
        System.out.println(callable2.get());
        Thread.sleep(10);
        System.out.println("==4、线程池方式创建2 end==");
    }
}

class ThreadDemo extends Thread {

    private String name;

    public ThreadDemo(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        System.out.println(String.format("%s ThreadDemo run...", name));
    }
}

class RunnableDemo implements Runnable {

    private String name;

    public RunnableDemo(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        System.out.println(String.format("%s RunnableDemo run...", name));
    }
}

class CallableDemo implements Callable<String> {

    private String name;

    public CallableDemo(String name) {
        this.name = name;
    }

    @Override
    public String call() {
        System.out.println(String.format("%s CallableDemo run...", name));
        return this.name;
    }
}

/**
 * 线程池
 */
@Configuration
@EnableAsync
class ThreadPoolConfig {

    @Bean(name = "taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(20);
        taskExecutor.setMaxPoolSize(50);
        taskExecutor.setQueueCapacity(5000);
        taskExecutor.setKeepAliveSeconds(600);
        taskExecutor.setThreadNamePrefix("taskExecutor--");
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        taskExecutor.setAwaitTerminationSeconds(6000);
        return taskExecutor;
    }
}

三、执行结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

楚风岸影

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

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

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

打赏作者

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

抵扣说明:

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

余额充值