线程池的使用,Callable和Runnable的使用

话不多说直接上代码

package com.mc.ThredPool;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import org.junit.Test;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;   
public class ThredPoolTest implements GuavaInteface {
    private static ListeningExecutorService pool;
    static {
        //通过guava创建固定容量的线程池,用完需要调用shutdown方法关闭线程池。
        pool = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(5));

    }

@Test
public void test() throws ExecutionException, InterruptedException {
    Instant now = Instant.now();
    Student st = new Student("付萌1", "女", 12, "高新");
    Student st2 = new Student("付萌1", "女", 13, "高新");
    Student st3 = new Student("付萌1", "女", 14, "高新");
    Student st4 = new Student("付萌1", "女", 15, "高新");
    Person p = new Person();
    copyDto(p, st);
    List result1 = new ArrayList<Student>();
    List result2 = new ArrayList<Person>();
    ListenableFuture<List> submit = pool.submit(() -> { //这里使用了lambda表达式,
        for (int i = 0; i < 100000000; i++) { //也可以直接通过匿名内部类实现callable,runnable区别,一个有返回值,一个没有返回值
            result1.add(st);
        }
        return result1;
    });
    ListenableFuture<List> submit1 = pool.submit(() -> {
        for (int i = 0; i < 100000000; i++) {
            result2.add(p);
        }
        return result2;
    });
    List list1 = submit.get();
    List list = submit1.get();
    pool.shutdown();//用完之后关闭线程池
    Instant now1 = Instant.now();
    System.out.println(list.size());
    System.out.println(list1.size());
    System.out.println("使用线程池耗时:"+Duration.between(now, now1).toMillis());
}
@Test
public void test1() throws ExecutionException, InterruptedException {
    Instant now = Instant.now();
    Student st = new Student("付萌1", "女", 12, "高新");
    Student st2 = new Student("付萌1", "女", 13, "高新");
    Student st3 = new Student("付萌1", "女", 14, "高新");
    Student st4 = new Student("付萌1", "女", 15, "高新");
    Person p = new Person();
    copyDto(p, st);
    List result1 = new ArrayList<Student>();
    List result2 = new ArrayList<Person>();
    for (int i = 0; i < 100000000; i++) {
        result1.add(st);
    }
    for (int i = 0; i < 100000000; i++) {
        result2.add(p);
    }

    Instant now1 = Instant.now();
    System.out.println(result1.size());
    System.out.println(result2.size());
    System.out.println("不使用线程池耗时:"+Duration.between(now, now1).toMillis());
}

}

实现Callable部分代码

	private static ExecutorService executorService = Executors.newFixedThreadPool(5);
	
	if(CollectionUtils.isNotEmpty(notPrintInfos)){
		List<Long> notOrderNos = notPrintInfos.stream().map(e -> e.getOrderNo()).collect(Collectors.toList());
		for (Long orderNo : notOrderNos) {
			notFutureList.add(executorService.submit(new Callable<OrderDetailDto>() {
				@Override
				public OrderDetailDto call() {
                    OrderDetailDto orderDetailDto = orderApiService.queryOrderDetailByOrderNo(orderNo);
                    int i = orderDetailDto.getOrderEntryDto() != null ? orderDetailDto.getOrderEntryDto().getOrderStatus() : 0;
                    if(RegexUtils.exist(i,new int[]{4,5,11,2,6})){ //6-揽收失败 11-受理失败
						return orderDetailDto;
                    }
                    return null;
				}
			}));
		}
	}

	for (Future future : notFutureList) {
		try {
			//执行到future.get()的时候线程在等待上面线程池里面的线程执行完再执行下面的
			OrderDetailDto orderDetailDto = future !=null?(OrderDetailDto)future.get():null;
			if(orderDetailDto != null){
				notOrderDetails.add(orderDetailDto);
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}

实现Runnable 部分代码

if (WechatUtils.USER_ART_SER.equals(content) || WechatUtils.USER_ART_SER_OR.equals(content)) {//直接转人工
							executorService.submit(new Runnable() {
								@Override
								public void run() {
									userToWechatService.sendMsgToXIAN(content, fromUserName, msgId);//123
								}
							});
						} 

与Callable不同的是Runnable 只是使用一个线程执行,主线程不需要这个线程的返回值,所以Runable里面执行的方法与主线程无关

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值