使用闭锁实现多线程联排

代码

import lombok.Data;

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

public class MyTest {
    public static void main(String[] args) {
        long l = System.currentTimeMillis();

        // 创建闭锁,需执行3个线程
        CountDownLatch countDownLatch = new CountDownLatch(3);

        // 线程1,计算 3 * 3,需执行1s
        Para para1 = new Para(3);
        ExecutorService thread1 = Executors.newSingleThreadExecutor();
        thread1.execute(() -> {
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            para1.setA(para1.getA() * para1.getA());
            countDownLatch.countDown();
        });

        // 线程2,计算 4 * 4,需执行3s
        Para para2 = new Para(4);
        ExecutorService thread2 = Executors.newSingleThreadExecutor();
        thread2.execute(() -> {
            try {
                Thread.sleep(3000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            para2.setA(para2.getA() * para2.getA());
            countDownLatch.countDown();
        });

        // 线程3,计算 5 * 5,需执行6s
        Para para3 = new Para(5);
        ExecutorService thread3 = Executors.newSingleThreadExecutor();
        thread3.execute(() -> {
            try {
                Thread.sleep(6000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            para3.setA(para3.getA() * para3.getA());
            countDownLatch.countDown();
        });

        // 三个线程执行完毕或超过后,继续执行,并关闭所有线程
        boolean await = false;
        try {
            // 超时时间4s
            await = countDownLatch.await(4L, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 关闭所有线程
            thread1.shutdown();
            thread2.shutdown();
            thread3.shutdown();
        }

        // 判断是否全部执行成功
        if (await) {
            System.out.println("执行成功,耗时:" + (System.currentTimeMillis() - l));
        } else {
            System.out.println("执行超时,部分执行失败,耗时:" + (System.currentTimeMillis() - l));
        }

        // 计算结果
        System.out.println(para1);
        System.out.println(para2);
        System.out.println(para3);
    }
}

@Data
class Para {
    private Integer a;

    public Para(Integer a) {
        this.a = a;
    }

    @Override
    public String toString() {
        return "Para [" +
                "a=" + a +
                ']';
    }
}

执行结果

超时时间设为10s时

image.png

超时时间设置为4s时

image.png

拓展

这里的示例是3个线程并行执行,拿到3个线程的执行结果。


image.png

如果想实现更复杂的线程联排,可直接在代码后面追加链路。


image.png

如果还需要更加复杂的组合的话可以使用京东的开源框架
asyncTool

你可能感兴趣的:(使用闭锁实现多线程联排)