Java并发学习之四种线程创建方式的实现与对比

在并发编程中,最基本的就是创建线程了,那么一般的创建姿势是怎样的,又都有些什么区别

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

  1. 继承Thread
  2. 实现Runnable接口
  3. 实现Callable接口,结合 FutureTask使用
  4. 利用该线程池来实现

演示案例: 创建两个线程并发实现从1-1000的累加

  1. 继承Thread实现线程创建
public class AddThread extends Thread {

    private int start, end;

    private int sum = 0;

    public AddThread(String name, int start, int end) {
        super(name);
        this.start = start;
        this.end = end;
    }
    public void run() {
        System.out.println("Thread-" + getName() + " 开始执行!");
        for (int i = start; i <= end; i ++) {
            sum += i;
        }
        System.out.println("Thread-" + getName() + " 执行完毕! sum=" + sum);
    }

    public static void main(String[] args) throws InterruptedException {
        int start = 0, mid = 500, end = 1000;

        AddThread thread1 = new AddThread("线程1", start, mid);
        AddThread thread2 = new AddThread("线程2", mid + 1, end);

        thread1.start();
        thread2.start();

        // 确保两个线程执行完毕
        thread1.join();
        thread2.join();

        int sum = thread1.sum + thread2.sum;
        System.out.println("ans: " + sum);
    }
}

输出结果:

Thread-线程1 开始执行!
Thread-线程2 开始执行!
Thread-线程1 执行完毕! sum=125250
Thread-线程2 执行完毕! sum=375250
ans: 500500

一般实现步骤:

继承 Thread 类
覆盖 run() 方法
直接调用 Thread#start() 执行

  1. 实现Runnable接口方式创建线程
public class AddRun implements Runnable {

    private int start, end;
    private int sum = 0;

    public AddRun(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " 开始执行!");
        for(int i = start; i <= end; i++) {
            sum += i;
        }
        System.out.println(Thread.currentThread().getName() + " 执行完毕! sum=" + sum);
    }


    public static void main(String[] args) throws InterruptedException {
        int start = 0, mid = 500, end = 1000;
        AddRun run1 = new AddRun(start, mid);
        AddRun run2 = new AddRun(mid + 1, end);
        Thread thread1 = new Thread(run1, "线程1");
        Thread thread2 = new Thread(run2, "线程2");

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();
        int sum = run1.sum + run2.sum;
        System.out.println("ans: " + sum);
    }
}

输出结果

线程2 开始执行!
线程1 开始执行!
线程2 执行完毕! sum=375250
线程1 执行完毕! sum=125250
ans: 500500

一般实现步骤:

实现Runnable接口
获取实现Runnable接口的实例,作为参数,创建Thread实例
执行 Thread#start() 启动线程
相比于继承Thread,这里是实现一个接口,最终依然是借助 Thread#start()来启动线程

  1. 实现Callable接口,结合FutureTask创建线程
    Callable接口相比于Runnable接口而言,会有个返回值,那么如何利用这个返回值呢?
public class AddCall implements Callable<Integer> {

    private int start, end;

    public AddCall(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    public Integer call() throws Exception {
        int sum = 0;
        System.out.println(Thread.currentThread().getName() + " 开始执行!");
        for (int i = start; i <= end; i++) {
            sum += i;
        }
        System.out.println(Thread.currentThread().getName() + " 执行完毕! sum=" + sum);
        return sum;
    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        int start = 0, mid = 500, end = 1000;
        FutureTask<Integer> future1 = new FutureTask<>(new AddCall(start, mid));
        FutureTask<Integer> future2 = new FutureTask<>(new AddCall(mid + 1, end));

        Thread thread1 = new Thread(future1, "线程1");
        Thread thread2 = new Thread(future2, "线程2");

        thread1.start();
        thread2.start();

        int sum1 = future1.get();
        int sum2 = future2.get();
        System.out.println("ans: " + (sum1 + sum2));
    }
}

输出结果

线程2 开始执行!
线程1 开始执行!
线程2 执行完毕! sum=375250
线程1 执行完毕! sum=125250
ans: 500500

一般实现步骤:

实现Callable接口
以Callable的实现类为参数,创建FutureTask实例
将FutureTask作为Thread的参数,创建Thread实例
通过 Thread#start 启动线程
通过 FutreTask#get() 阻塞获取线程的返回值
Callable接口相比Runnable而言,会有结果返回,因此会由FutrueTask进行封装,以期待获取线程执行后的结果;最终线程的启动都是依赖Thread#start

  1. 线程池方式创建
    创建固定大小的线程池,提交Callable任务,利用Future获取返回的值
public class AddPool implements Callable<Integer> {
    private int start, end;

    public AddPool(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    public Integer call() throws Exception {
        int sum = 0;
        System.out.println(Thread.currentThread().getName() + " 开始执行!");
        for (int i = start; i <= end; i++) {
            sum += i;
        }
        System.out.println(Thread.currentThread().getName() + " 执行完毕! sum=" + sum);
        return sum;
    }

    public static void main(String[] arg) throws ExecutionException, InterruptedException {
        int start=0, mid=500, end=1000;
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        Future<Integer> future1 = executorService.submit(new AddPool(start, mid));
        Future<Integer> future2 = executorService.submit(new AddPool(mid+1, end));

        int sum = future1.get() + future2.get();
        System.out.println("sum: " + sum);
    }
}

输出

pool-1-thread-1 开始执行!
pool-1-thread-2 开始执行!
pool-1-thread-1 执行完毕! sum=125250
pool-1-thread-2 执行完毕! sum=375250
sum: 500500

一般实现逻辑:

创建线程池(可以利用JDK的Executors,也可自己实现)
创建Callable 或 Runnable任务,提交到线程池
通过返回的 Future#get 获取返回的结果
II. 对比分析

  1. 分类
    上面虽然说是有四种方式,但实际而言,主要划分为两类
    继承Thread类,覆盖run方法填写业务逻辑
    实现Callable或Runnable接口,然后通过Thread或线程池来启动线程
    此外,还有一种利用Fork/Join框架来实现并发的方式,后续专门说明,此处先略过
  2. 区分说明
    继承和实现接口的区别
    先把线程池的方式拎出来单独说,这里主要对比Thread, Callable, Runnable三中方式的区别

Executors类,提供了一系列工厂方法用于创建线程池,返回的线程池都实现了ExecutorService接口:

public static ExecutorService newFixedThreadPool(int nThreads) ;//创建固定数目线程的线程池。
public static ExecutorService newCachedThreadPool();//创建一个可缓存的线程池,调用execute 将重用以前构造的线程(如果线程可用)。如果现有线程没有可用的,则创建一个新线程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。
public static ExecutorService newSingleThreadExecutor();//创建一个单线程化的Executor。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize);//创建一个支持定时及周期性的任务执行的线程池,多数情况下可用来替代Timer类。

ExecutoreService提供了submit()方法,传递一个Callable,或Runnable,返回Future。如果Executor后台线程池还没有完成Callable的计算,这调用返回Future对象的get()方法,会阻塞直到计算完成。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值