浅谈创建线程的几种方式

创建线程一般有四种方式:

  1. 继承Thread类
  2. 实现Runnable接口
  3. 实现Callable接口
  4. 使用线程池

下面介绍这几种方式的简单使用

继承Thread类

使用方式:
(1)创建一个类继承Thread类
(2)重写run()方法
(3)调用start()方法开启线程

public class ThreadDemo extends Thread {

    @Override
    public void run() {
        System.out.println("继承Thread类的线程");
    }

    public static void main(String[] args) {
        ThreadDemo threadDemo = new ThreadDemo();
        // 开启线程
        threadDemo.start();
        System.out.println("主线程");
    }
}

实现Runnable接口

使用方式:
(1)创建一个类实现Runnable接口
(2)实现run()方法
(3)调用start()方法开启线程

public class RunnableDemo implements Runnable {

    @Override
    public void run() {
        System.out.println("实现Runnable接口的线程");
    }

    public static void main(String[] args) {
        RunnableDemo runnableDemo = new RunnableDemo();
        Thread thread = new Thread(runnableDemo);
        // 启动线程
        thread.start();
        System.out.println("主线程");
    }

}

实现Callable接口

使用方式:
(1)创建一个类实现Callable接口
(2)实现call()方法
(3)调用start()方法开启线程
注:实现Callable接口的线程执行结束后会有返回值;返回值的类型在实现Callable接口的时候定义

public class CallableDemo implements Callable<String> {

    @Override
    public String call() throws Exception {
        System.out.println("实现Callable接口的线程");
        return "success";
    }

    public static void main(String[] args) {
        CallableDemo callableDemo = new CallableDemo();
        FutureTask<String> task = new FutureTask<String>(callableDemo);
        Thread thread = new Thread(task);
        // 开启线程
        thread.start();
        System.out.println("主线程");
        try {
            // 获取线程执行结果
            System.out.println(task.get());
        } catch (InterruptedException e) {
            System.out.println("InterruptedException");
        } catch (ExecutionException e) {
            System.out.println("ExecutionException");
        }
    }

}

使用线程池创建

使用方式:
(1)创建一个自定义参数的线程池
(2)调用execute()方法执行创建的线程
(3)关闭线程池

public class ThreadPoolDemo {

    /**
     * 核心线程数
     */
    private static final int CORE_SIZE = 5;

    /**
     * 最大线程数
     */
    private static final int MAXIMUM_POOL_SIZE = 10;

    /**
     * 大于核心线程数的多余空闲线程的存活时间
     */
    private static final long KEEP_ALIVE_TIME = 20L;

    /**
     * 时间单位,可根据TimeUnit自定义设置
     */
    private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;

    /**
     * 阻塞队列,可自定义类型
     */
    private static final BlockingQueue<Runnable> BLOCKING_QUEUE = new ArrayBlockingQueue<>(20);

    public static void main(String[] args) {
        // 自定义一个线程池
        ThreadPoolExecutor threadPoolExecutor =
                new ThreadPoolExecutor(CORE_SIZE, MAXIMUM_POOL_SIZE,
                 KEEP_ALIVE_TIME, TIME_UNIT, BLOCKING_QUEUE);
        for (int i = 0; i < 6; i++) {
            threadPoolExecutor.execute(()->{
                System.out.println("线程:" + Thread.currentThread().getName() + "正在执行...");
            });
        }
        // 关闭线程池
        threadPoolExecutor.shutdown();
    }
}

总结

目前使用最多的是使用线程池创建线程的方式;因为使用线程池管理线程,省去了频繁的创建和销毁线程的时间;

note:有疑问请大家留言,谢谢

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值