java主线程等待多个子线程中任意一个有结果后,主线程继续执行

1.背景

2.代码

package com.qianxingniwo.ls;

import org.junit.Test;

import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;

/**
 * @Copyright (C) XXXXX技有限公司
 * @Author: ldp
 * @Date: 2023/7/26 15:30
 * @Description:
 */
public class Demo01 {

    /**
     * 测试:
     */
    @Test
    public void test01() {
        Thread threadMain = Thread.currentThread();
        AtomicReference<String> result = new AtomicReference<>("");

        Thread thread1 = new Thread(() -> {
            System.out.println("1");
            try {
                Thread.sleep(5 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("1-结束");
        });

        Thread thread2 = new Thread(() -> {
            System.out.println("2");
            try {
                Thread.sleep(3 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("2-结束");
        });

        Thread thread3 = new Thread(() -> {
            System.out.println("3");
            try {
                Thread.sleep(1 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            result.set("线程3返回了结果");
            LockSupport.unpark(threadMain);
            System.out.println("3-结束");
        });
        thread1.start();
        thread2.start();
        thread3.start();

        System.out.println("主线程等待结果");
        LockSupport.park(this);
        System.out.println("主线程获得了结果:" + result.get());
        try {
            Thread.sleep(6 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("执行完成...");
    }
}

 

完美

posted @ 2023-07-26 16:24  李东平|一线码农  阅读(71)  评论(0编辑  收藏  举报