Java-JUC(十二):有3个线程。线程A和线程B并行执行,线程C需要A和B执行完成后才能执行。可以怎么实现?

实现代码:

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;

public class TestABC {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch=new CountDownLatch(2);
        Semaphore semaphoreC = new Semaphore(1);
        
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(newjava.util.Random().nextInt(1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName());
                countDownLatch.countDown();
            }
        }, "Thread-A");

        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(newjava.util.Random().nextInt(1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName());
                countDownLatch.countDown();
            }
        }, "Thread-B");

        Thread threadC = new Thread(new Runnable() {
            @Override
            public void run() {                
                try {
                    semaphoreC.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName());
                semaphoreC.release();
            }
        }, "Thread-C");
        
        // 占用C锁,直到A/B线程完成后,才释放C锁。
        semaphoreC.acquire();
        
        threadA.start();
        threadB.start();
        threadC.start();
        
        countDownLatch.await(); 
        // 释放C锁,让C线程有获取锁的可能
        semaphoreC.release();
        
    }
}

猜你喜欢

转载自www.cnblogs.com/yy3b2007com/p/11319034.html
今日推荐