Spring Boot教程十五:多线程

实际的开发应该开发过程中,经常需要使用到多线程,而且大多时候需要获取到每个线程执行的结果,然后再执行剩下的业务逻辑。具体实现如下;

pom文件引用:

       <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>18.0</version>
        </dependency>

线程任务处理类;

package com.ganinfo.test;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;

/**
 * @author Shuyu.Wang
 * @package:com.ganinfo.test
 * @className:
 * @description:
 * @date 2018-10-28 19:35
 **/
@Slf4j
public class AuthCallable implements Callable {

    private AuthType authType;
    /**
     * 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 Object call() throws Exception {
        if ("1".equals(authType.getType())){
            log.info("方式一"+authType.getName()+"授权start");
            Thread.sleep(8000);
            log.info("方式一授权end");
            return authType.getName();
        }
        if ("2".equals(authType.getType())){
            log.info("方式二"+authType.getName()+"授权start");
            Thread.sleep(7000);
            log.info("方式二授权end");
            return authType.getName();
        }
        if ("3".equals(authType.getType())){
            log.info("方式三"+authType.getName()+"授权start");
            Thread.sleep(5000);
            log.info("方式三授权end");
            return authType.getName();
        }
        if ("4".equals(authType.getType())){
            log.info("方式四"+authType.getName()+"授权start");
            Thread.sleep(3000);
            log.info("方式四授权end");
            return authType.getName();
        }
        if ("5".equals(authType.getType())){
            log.info("方式五"+authType.getName()+"授权start");
            Thread.sleep(1000);
            log.info("方式五授权end");
            return authType.getName();
        }

        return null;
    }

    public void setAuthType(AuthType authType) {
        this.authType = authType;
    }
}

引用的POJO类型:

package com.ganinfo.test;

import lombok.Data;

/**
 * @author Shuyu.Wang
 * @package:com.ganinfo.test
 * @className:
 * @description:
 * @date 2018-10-28 19:34
 **/
@Data
public class AuthType {
    private String type;
    private String name;
}

业务实现类:

package com.ganinfo.test;

import com.ganinfo.utils.GsonUtil;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author Shuyu.Wang
 * @package:com.ganinfo.test
 * @className:
 * @description:
 * @date 2018-10-28 19:41
 **/
@Service
@Slf4j
public class AuthService {

    public void auth(String a) {
        long start=System.currentTimeMillis();
        List<String> list = new ArrayList<>();
        int count=5;
        try {
            final CountDownLatch countDownLatch = new CountDownLatch(count);
            ExecutorService executorService = Executors.newFixedThreadPool(8);
            ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(executorService);

            for (int i = 1; i <= count; i++) {
                AuthCallable authCallable = new AuthCallable();
                AuthType authType = new AuthType();
                authType.setType(String.valueOf(i));
                authType.setName(String.valueOf(i) + "名称");
                authCallable.setAuthType(authType);
                ListenableFuture listenableFuture = listeningExecutorService.submit(authCallable);
                Futures.addCallback(listenableFuture, new FutureCallback<String>() {
                    @Override
                    public void onSuccess(String name) {
                        log.info("授权结果" + name);
                        list.add(name);
                        countDownLatch.countDown();
                    }

                    @Override
                    public void onFailure(Throwable throwable) {
                        countDownLatch.countDown();
                        log.info("处理出错:", throwable);

                    }
                });
            }
                 try {
                        executorService.shutdown();
                      //shutdown调用后,不可以再submit新的task,已经submit的将继续执行。
                        if (!countDownLatch.await(15, TimeUnit.MINUTES)) {
                            log.info("超时的时候向线程池中所有的线程发出中断");
                            // 超时的时候向线程池中所有的线程发出中断(interrupted)。
                            executorService.shutdownNow();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        executorService.shutdownNow();
                         //shutdownNow试图停止当前正执行的task,并返回尚未执行的task的list
                    }
            log.info("执行结果" + GsonUtil.GsonString(list));
            long end=System.currentTimeMillis();
            log.info("用时" + (end-start));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

执行结果如下:

2018-10-28 20:16:49.510  INFO [alarmservice1,,,] 34204 --- [ool-13-thread-1] com.ganinfo.test.AuthCallable            : 方式一1名称授权start
2018-10-28 20:16:49.522  INFO [alarmservice1,,,] 34204 --- [ool-13-thread-2] com.ganinfo.test.AuthCallable            : 方式二2名称授权start
2018-10-28 20:16:49.522  INFO [alarmservice1,,,] 34204 --- [ool-13-thread-3] com.ganinfo.test.AuthCallable            : 方式三3名称授权start
2018-10-28 20:16:49.522  INFO [alarmservice1,,,] 34204 --- [ool-13-thread-4] com.ganinfo.test.AuthCallable            : 方式四4名称授权start
2018-10-28 20:16:49.522  INFO [alarmservice1,,,] 34204 --- [ool-13-thread-5] com.ganinfo.test.AuthCallable            : 方式五5名称授权start
2018-10-28 20:16:50.523  INFO [alarmservice1,,,] 34204 --- [ool-13-thread-5] com.ganinfo.test.AuthCallable            : 方式五授权end
2018-10-28 20:16:50.523  INFO [alarmservice1,,,] 34204 --- [ool-13-thread-5] com.ganinfo.test.AuthService             : 授权结果5名称
2018-10-28 20:16:52.523  INFO [alarmservice1,,,] 34204 --- [ool-13-thread-4] com.ganinfo.test.AuthCallable            : 方式四授权end
2018-10-28 20:16:52.523  INFO [alarmservice1,,,] 34204 --- [ool-13-thread-4] com.ganinfo.test.AuthService             : 授权结果4名称
2018-10-28 20:16:54.523  INFO [alarmservice1,,,] 34204 --- [ool-13-thread-3] com.ganinfo.test.AuthCallable            : 方式三授权end
2018-10-28 20:16:54.523  INFO [alarmservice1,,,] 34204 --- [ool-13-thread-3] com.ganinfo.test.AuthService             : 授权结果3名称
2018-10-28 20:16:56.523  INFO [alarmservice1,,,] 34204 --- [ool-13-thread-2] com.ganinfo.test.AuthCallable            : 方式二授权end
2018-10-28 20:16:56.523  INFO [alarmservice1,,,] 34204 --- [ool-13-thread-2] com.ganinfo.test.AuthService             : 授权结果2名称
2018-10-28 20:16:57.512  INFO [alarmservice1,,,] 34204 --- [ool-13-thread-1] com.ganinfo.test.AuthCallable            : 方式一授权end
2018-10-28 20:16:57.512  INFO [alarmservice1,,,] 34204 --- [ool-13-thread-1] com.ganinfo.test.AuthService             : 授权结果1名称
2018-10-28 20:16:57.515  INFO [alarmservice1,,,] 34204 --- [           main] com.ganinfo.test.AuthService             : 执行结果["5名称","4名称","3名称","2名称","1名称"]
2018-10-28 20:16:57.515  INFO [alarmservice1,,,] 34204 --- [           main] com.ganinfo.test.AuthService             : 用时8013

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值