4个子线程计数,每个线程都计数25次

  要求主线程执行在子线程执行之后。
这个很好办,子线程都设为不是守护线程

然后处理4个子线程

我们可以让每个线程向如下

static class MyThread {
        public static void start(int begin, int step){
            Thread t = new Thread(()->{
                int localSum = 0;
                for (int i = begin;i<=100;i+=step){
                    localSum+=i;
                }
            });
            t.setDaemon(false);
            t.start();
        }
    }
}

在建立一个阻塞队列,存每个任务块的结果

 private static final LinkedBlockingQueue<Integer> queue = 
 new LinkedBlockingQueue<>(10);

将子线程执行结果放入阻塞队列

queue.offer(localSum);

使用并发包的原子类对结果进行累加

 private static final AtomicInteger sum = new AtomicInteger(0);
 public static void test3()throws InterruptedException{
        int sum = 0;
        Lock lock = new ReentrantLock();
        AtomicInteger count = new AtomicInteger(0);
        for(int i = 0 ; ;i++){
            MyThread.start(i,4);
            count.getAndIncrement();
            if(i==4){
                break;
            }
        }
        while(count.decrementAndGet()>0){
            Integer integer = null;
            while(queue.size()<=0){
                Thread.sleep(0);
            }
            lock.lock();
            integer = queue.take();
            lock.unlock();
            sum+=Integer.valueOf(integer);
        }
        System.out.println(sum);
    }

这样就能可以解决问题
完整代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值