Java项目中多线程的使用

一、线程池创建

如果需要在项目中使用多线程,那么一定要先创建线程池。因为线程池可以达到线程复用,节省反复创建和销毁的开销。提升性能。就跟平时项目中使用的数据库连接池是一个道理。

首先来看一下线程池创建的方法:

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

 int corePoolSize,         核心线程数

int maximumPoolSize, 最大线程数

 long keepAliveTime, 线程没有任务时的存活时间

 TimeUnit unit, 时间单位

BlockingQueue<Runnable> workQueue  一个阻塞队列,用来存储等待执行的任务,这个参数的选择也很重要,会对线程池的运行过程产生重大影响,一般来说,这里的阻塞队列有以下几种选择 :

ArrayBlockingQueue;
LinkedBlockingQueue;
SynchronousQueue;

 ThreadFactory threadFactory,       线程工厂,主要用来创建线程

 RejectedExecutionHandler handler 表示当拒绝处理任务时的策略,有以下四种取值:   ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。   ThreadPoolExecutor.DiscardPolicy:也是丢弃任务,但是不抛出异常。     ThreadPoolExecutor.DiscardOldestPolicy:丢弃队列最前面的任务,然后重新尝试执行任务(重复此过程)

ThreadPoolExecutor.CallerRunsPolicy:由调用线程处理该任务

 根据上面的方法我们就可以开始创建我们的线程池了

//创建有界队列,防止内存溢出
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(1024);
#使用hutool的NamedThreadFactory   hutool是一个非常好用的工具类集合
ThreadFactory threadFactory = new NamedThreadFactory("测试",false);
ThreadPoolExecutor es = new ThreadPoolExecutor(
                8,
                16,
                1, TimeUnit.SECONDS,
                workQueue,threadFactory);

这样我的线程池就创建完成了。

二、根据业务选择线程的创建

如果有返回值那就实现Callable接口,否则就实现Runnable接口

现在假设我们有一个需要返回结果的业务,那该如何实现呢?接下来直接上代码:

public static class Task implements Callable<String>{

        /**
         * Computes a result, or throws an exception if unable to do so.
         *
         * @return computed result
         * @throws Exception if unable to compute a result
         */
        @Override
        public String call() throws Exception {
           
            return Thread.currentThread().getName();
        }
    }

这样就算是实现了Callable接口了,但是正常的业务我们肯定需要处理业务的,那就必定会需要接受参数。所以我们的这个类还必须要添加一个构造方法去接收参数。代码如下:

public static class Task2 implements Callable<String>{

        private String name;

        private int age;

        public Task2(String name, int age) {
            this.name = name;
            this.age = age;
        }

        /**
         * Computes a result, or throws an exception if unable to do so.
         *
         * @return computed result
         * @throws Exception if unable to compute a result
         */
        @Override
        public String call() throws Exception {
            System.out.println("name = " + name);
            System.out.println("age = " + age);
            //处理业务逻辑
            //返回处理结果
            return Thread.currentThread().getName();
        }
    }

注意:Callable<> 返回的参数是可以自定义的 

比如:Callable<Student>   返回对象   Callable<String>   返回字符串

 三、完整代码

package com.xingli.springlearningdemo.stream;

import cn.hutool.core.thread.NamedThreadFactory;

import java.util.*;
import java.util.concurrent.*;

/**
 * description: streamTest <br>
 *
 * @date: 2021/6/11 0011 下午 1:35 <br>
 * @author: William <br>
 * version: 1.0 <br>
 */

public class streamTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        List<Future<String>> futureList = new ArrayList<>();
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(1024);
        ThreadFactory threadFactory = new NamedThreadFactory("测试",false);
        ThreadPoolExecutor es = new ThreadPoolExecutor(8,16,3, TimeUnit.SECONDS,workQueue,threadFactory);
        for (int i = 0; i < 100; i++) {
            try{
                futureList.add(es.submit(new Task()));
                System.out.println("当前排队线程数:= " + es.getQueue().size());
                System.out.println("当前活动线程数:= " + es.getActiveCount());
                System.out.println("===============================");
            }catch (Exception e){
                System.out.println("异常");
            }
        }
        es.shutdown();
        System.out.println("线程结束===============================");
        for (Future<String> stringFuture : futureList) {
            System.out.println(stringFuture.get().toString());
        }
    }


    public static class Task implements Callable<String>{

        /**
         * Computes a result, or throws an exception if unable to do so.
         *
         * @return computed result
         * @throws Exception if unable to compute a result
         */
        @Override
        public String call() throws Exception {
            Thread.sleep(10);
            return Thread.currentThread().getName();
        }
    }

    public static class Task2 implements Callable<String>{

        private String name;

        private int age;

        public Task2(String name, int age) {
            this.name = name;
            this.age = age;
        }

        /**
         * Computes a result, or throws an exception if unable to do so.
         *
         * @return computed result
         * @throws Exception if unable to compute a result
         */
        @Override
        public String call() throws Exception {
            System.out.println("name = " + name);
            System.out.println("age = " + age);
            return Thread.currentThread().getName();
        }
    }

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值