使用Java ThreadFactory 线程池

场景:

学校组织15个学生去拨一颗萝卜,每3个学生一组,各组全部完成拨萝卜后,然后公布结果

使用多线程进行实现

package com;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.*;
/**
 * 需求,使用
 * 学校组织15个学生去拨一颗萝卜,每3个学生一组,各组全部完成拨萝卜后,公布结果
 * 
 */
public class TestThread {
    public static void main(String[] args) throws InterruptedException {
        List<ConcurrentHashMap> personList = new ArrayList<ConcurrentHashMap>();
        //模拟15个学生
        for (int i=1;i<=15;){
            ConcurrentHashMap person = new ConcurrentHashMap();
            person.put("姓名:","学生("+(i++)+")");
            personList.add(person);
        }
        //每组人数(3人)
        int groupPersonSize = 3;
        //按照每三人一组进行分组
        List<List<ConcurrentHashMap>> partition = Lists.partition(personList, groupPersonSize);
        //组数(计算一共几组)
        int groups = partition.size();
        //创建线程池
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("apxs-Thread -%d").build();
        ExecutorService singleThreadPool = new ThreadPoolExecutor(
                groups, Integer.MAX_VALUE,200L
                , TimeUnit.MILLISECONDS
                ,new LinkedBlockingQueue<>(1024)
                , namedThreadFactory
                , new ThreadPoolExecutor.AbortPolicy()
        );
        //使用线程安全的Vector,作为计数器。
        List dataCount = new Vector();
        //根据组数,启动线程
        long startTime=System.currentTimeMillis();
        for (int i = 0; i < groups; i++) {
            int finalI = i;
            singleThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    dataCount.add(1);
                    List<ConcurrentHashMap> dbSources = partition.get(finalI);
                    System.out.printf("我是第%d小组,组内学生包含:%s,用时%s秒完成拨萝卜\n",finalI+1,dbSources.toString(),((float)(System.currentTimeMillis()-startTime)/1000));
                }
            });
        }
        singleThreadPool.shutdown();
        System.out.println("===========公布结果,如下===========");
        System.out.printf("本次分为%s组,以完成%s组",groups,dataCount.size());
    }
}

 下面是错误的输出结果,如下:


 
 

输出结果并不是需求描述中“分组完成后,才公布结果”,原因分析如下:

因为线程没有结束,就“公布结果”了。


解决方案:

可以使用CountDownLatch允许一个或者多个线程去等待其他线程完成操作。

package com;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.*;
/**
 * 需求,使用
 * 学校组织15个学生去拨一颗萝卜,每3个学生一组,各组全部完成拨萝卜后,公布结果
 * 
 */
public class TestThread {
    public static void main(String[] args) throws InterruptedException {
        List<ConcurrentHashMap> personList = new ArrayList<ConcurrentHashMap>();
        //模拟15个学生
        for (int i=1;i<=15;){
            ConcurrentHashMap person = new ConcurrentHashMap();
            person.put("姓名:","学生("+(i++)+")");
            personList.add(person);
        }
        //每组人数(3人)
        int groupPersonSize = 3;
        //按照每三人一组进行分组
        List<List<ConcurrentHashMap>> partition = Lists.partition(personList, groupPersonSize);
        //组数(计算一共几组)
        int groups = partition.size();
        //创建线程池
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("apxs-Thread -%d").build();
        ExecutorService singleThreadPool = new ThreadPoolExecutor(
                groups, Integer.MAX_VALUE,200L
                , TimeUnit.MILLISECONDS
                ,new LinkedBlockingQueue<>(1024)
                , namedThreadFactory
                , new ThreadPoolExecutor.AbortPolicy()
        );
        //使用线程安全的Vector,作为计数器。
        List dataCount = new Vector();
        //使用CountDownLatch允许一个或者多个线程去等待其他线程完成操作。
        CountDownLatch latch = new CountDownLatch(groups);
        //根据组数,启动线程
        long startTime=System.currentTimeMillis();
        for (int i = 0; i < groups; i++) {
            int finalI = i;
            singleThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    dataCount.add(1);
                    List<ConcurrentHashMap> dbSources = partition.get(finalI);
                    System.out.printf("我是第%d小组,组内学生包含:%s,用时%s秒完成拨萝卜\n",finalI+1,dbSources.toString(),((float)(System.currentTimeMillis()-startTime)/1000));
                    //使latch的值减1,如果减到了0,则会唤醒所有等待在这个latch上的线程。
                    latch.countDown();
                }
            });
        }
        //使当前线程进入同步队列进行等待,直到latch的值被减到0或者当前线程被中断,当前线程就会被唤醒。
        latch.await();
        singleThreadPool.shutdown();
        System.out.println("===========公布结果,如下===========");
        System.out.printf("本次分为%s组,以完成%s组",groups,dataCount.size());
    }
}

下面是正确的输出结果:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

D哈迪斯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值