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("執行完成...");
    }
}

 

完美

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章