多线程Runnable、CountDownLatch运行代码示例

Runnable 示例代码
CountDownLatch 示例代码

package com.doggy.doggy;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @desc 多线程示例
 * @author ashly
 * @date 2020/1/15 9:55
 **/
@Slf4j
public class ThreadExample {
    //创建2个线程用于处理任务
    private static final ExecutorService executor = Executors.newFixedThreadPool(2);

    public static void main(String[] args){
        int count = 10;
        //任务计数
        CountDownLatch latch = new CountDownLatch(count);
        System.out.println("提交任务");
        for (int i = 0; i < count; i++) {
            executor.submit(new DemoRunnable(i, latch));
        }

        //任务等待
        try {
            latch.await();//等待,当计数latch减到0时,所有线程并行执行
        } catch (InterruptedException e) {
            log.info("Thread Interrupted!");
            Thread.currentThread().interrupt();
        }
        System.out.println("执行完毕");
    }
}

class DemoRunnable implements Runnable {
    int anInt;
    CountDownLatch latch;

    DemoRunnable(int anInt, CountDownLatch latch){
        this.anInt = anInt;
        this.latch = latch;
    }

    @Override
    public void run() {
        if (anInt == 3 || anInt == 5 || anInt == 9){//模拟不同任务的处理时间不同
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("执行完第" + (anInt + 1) + "个任务,latch's count: " + latch.getCount() );
        latch.countDown();
    }
}

运行结果

提交任务
执行完第1个任务,latch’s count: 10
执行完第3个任务,latch’s count: 9
执行完第2个任务,latch’s count: 8
执行完第5个任务,latch’s count: 7
执行完第6个任务,latch’s count: 6
执行完第4个任务,latch’s count: 6
执行完第7个任务,latch’s count: 5
执行完第8个任务,latch’s count: 4
执行完第9个任务,latch’s count: 3
执行完第10个任务,latch’s count: 1
执行完毕

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值