【技能库】--批量任务多线程并发执行(324)

扩展callable 接口 并且  Futrue<?> 




import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Uninterruptibles;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Random;
import java.util.Stack;
import java.util.concurrent.*;

/**
 * Created by xiayin on 2017/9/16.
 */
public class ConcurrentThreadTest {
    //List 任务
    //每次取制定个数任务
    //任务扩展callable
    //指定线程池执行任务 200ms内没有执行完毕的下次不再提取
    //循环执行

    private static Stack<TaskWithId> stack = new Stack<>();
    private static ExecutorService pool = Executors.newFixedThreadPool(3);
    private static int countDownNumber = 3;


    public static void main(String[] args) {

        moskListTask();

        while (true) {
            List<Integer> doneList = Lists.newArrayList();
            CountDownLatch latch = new CountDownLatch(countDownNumber);
            List<TaskWithId> taskWithIds = pullFixNumTask(countDownNumber);

            StringBuilder bi = new StringBuilder();
            for (TaskWithId taskWithId : taskWithIds) {
                bi.append(taskWithId.id).append(" ");
            }
            System.out.println("本次需要执行的任务 ids = " + bi.toString());

            if (CollectionUtils.isEmpty(taskWithIds)) {
                break;
            }
            List<Future<Integer>> result = Lists.newArrayList();
            for (TaskWithId taskWithId : taskWithIds) {
                taskWithId.setLatch(latch);
                result.add(pool.submit(taskWithId));
            }
            //等待latch 设置过期时间
            Uninterruptibles.awaitUninterruptibly(latch, 20, TimeUnit.MICROSECONDS);

            //每个任务等待指定时间 不中断实际任务的执行 获取结果
            for (Future<Integer> future : result) {
                try {
                    Uninterruptibles.getUninterruptibly(future, 1, TimeUnit.SECONDS);//非中断获取结果
                    doneList.add(future.get());
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    System.out.println("任务超时");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            StringBuilder ri = new StringBuilder();
            for (Integer integer : doneList) {
                ri.append(integer).append(" ");
            }
            System.out.println();
            System.out.println("本次完成的任务 ids = " + ri.toString());


        }
    }


    private static List<TaskWithId> pullFixNumTask(int num) {
        List<TaskWithId> list = Lists.newArrayList();
        while (!stack.isEmpty() && num > 0) {
            num--;
            list.add(stack.pop());
           // System.out.println("取出任务");
        }
        return list;
    }


    private static List<TaskWithId> moskListTask() {
        for (int i = 0; i < 10; i++) {
            stack.push(new TaskWithId(i));
        }
        System.out.println("所有的任务集合=" + JSON.toJSONString(stack.elements()));
        return stack;
    }


    static class TaskWithId implements Callable {
        private int id;
        private CountDownLatch latch;

        public void setLatch(CountDownLatch latch) {
            this.latch = latch;
        }


        TaskWithId(int id) {
            this.id = id;
        }


        public void run() {
            try {
                Thread.sleep(new Random().nextInt(500) * id);

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                latch.countDown();
            }
        }

        @Override
        public Object call() throws Exception {
            run();
            System.out.println("done "+id );
            return id;
        }

        @Override
        public String toString() {
            return ToStringBuilder.reflectionToString(this);
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

自驱

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

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

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

打赏作者

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

抵扣说明:

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

余额充值