JDK5.0之后新增的线程创建方式

这篇博客介绍了Java中实现多线程的两种方式:通过实现Callable接口和使用线程池。Callable接口允许创建带有返回值的线程,并能抛出异常。线程池则通过ExecutorService提供了线程管理和资源优化,如固定线程池可以减少创建线程的时间和资源消耗。示例代码展示了如何创建和使用这两个方法。

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

在这里插入图片描述

package com.atguigu.java2;

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

/**
 * 创建线程的方式三:实现Callable接口, ---JDK5.0新增
 * 1.创建一个实现Callable接口的实现类
 * 2.实现call方法,将此线程需要执行的操作声明在call()方法中
 * 3.创建Callable接口实现类的对象
 * 4.将Callable接口实现类的对象作为传递到FutureTask构造器中,创建FutureTask的对象
 * 5.将FutureTask的对象作为参数传递到Thread类的构造器中,创建Thread对象,并调用start()
 * 6.获取Callable中call方法的返回值
 * <p>
 * 如何理解实现Callable接口的方式创建多线程比实现Runnable接口创建多线程方式强大?
 * 1.call()可以有返回值的
 * 2.call(可以抛出异常,被外面的操作捕获,获取异常信息
 * 3.Callable是支持泛型的
 *
 * @author shkstart
 * @create 2021-08-27 13:40
 */

class NumberThread implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 0; i <= 100; i++) {
            if (i % 2 == 0) {
                System.out.println(i);
                sum += i;
            }

        }
        return sum;
    }
}


public class ThreadNew {
    public static void main(String[] args) {
        NumberThread numberThread = new NumberThread();
        FutureTask<Integer> futureTask = new FutureTask<Integer>(numberThread);
        new Thread(futureTask).start();
        try {
            //get()返回值即为FutureTask构造器参数Callable实现类重写call()的返回值
            Integer sum = futureTask.get();
            System.out.println("总和为:" + sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

在这里插入图片描述

package com.atguigu.java2;

import java.lang.reflect.Executable;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 创建线程的方式四:使用线程池
 * 好处:
 *  提高响应速度(减少了创建新线程的时间)
 *  降低资源消耗(重复利用线程池中线程,不需要每次都创建)
 *  便于线程管理
 * corePoolSize:核心池的大小
 * maximumPoolSize:最大线程数  keepAliveTime:线程没有任务时最多保持多长时间后会终止
 *
 * 面试题:创建多线程有几种方式?四种,继承Thread,实现Runnable接口,实现Callable接口
 * 线程池
 * ExecutorService service = Executors.newFixedThreadPool(10);
 *
 * @author shkstart
 * @create 2021-08-27 14:32
 */

class NumberThread7 implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}

class NumberThread8 implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            if (!(i % 2 == 0)) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}

public class ThreadPool {
    public static void main(String[] args) {
        //提供指定线程数量的线程池
        ExecutorService service = Executors.newFixedThreadPool(10);//多态
        ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;//强转
        service1.setCorePoolSize(15);
        //service1.setKeepAliveTime();
        //设置线程池的属性
        //System.out.println(service.getClass());
        //执行指定的线程的操作,需要提供实现Runnable接口或Callable接口实现类的对象
        service.execute(new NumberThread7());//适合使用于Runnable
        service.execute(new NumberThread8());//适合使用于Runnable
        //service.submit();//适合使用于Callable
        service.shutdown();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值