LeetCode 1114. 按序打印

题目描述

1114. 按序打印

思路分析

解法一:信号量 / 闭锁(推荐)

核心思路

  • 第一段打印完成后释放信号,第二段等待该信号。
  • 第二段打印完成后释放另一个信号,第三段等待该信号。
  • 使用 CountDownLatch 或 channel 进行同步。


复杂度分析

  • 时间复杂度:O(1),只涉及固定同步与打印。
  • 空间复杂度:O(1)。
import java.util.concurrent.CountDownLatch;

class Foo {
    private final CountDownLatch firstDone = new CountDownLatch(1);
    private final CountDownLatch secondDone = new CountDownLatch(1);

    public Foo() {}

    public void first(Runnable printFirst) throws InterruptedException {
        printFirst.run();
        firstDone.countDown();
    }

    public void second(Runnable printSecond) throws InterruptedException {
        firstDone.await();
        printSecond.run();
        secondDone.countDown();
    }

    public void third(Runnable printThird) throws InterruptedException {
        secondDone.await();
        printThird.run();
    }
}
type Foo struct {
	firstDone  chan struct{}
	secondDone chan struct{}
}

func NewFoo() Foo {
	return Foo{
		firstDone:  make(chan struct{}),
		secondDone: make(chan struct{}),
	}
}

func (f *Foo) first(printFirst func()) {
	printFirst()
	close(f.firstDone)
}

func (f *Foo) second(printSecond func()) {
	<-f.firstDone
	printSecond()
	close(f.secondDone)
}

func (f *Foo) third(printThird func()) {
	<-f.secondDone
	printThird()
}

相似题目

题目 难度 考察点
1115. 交替打印 FooBar 中等 并发同步
1116. 打印零与奇偶数 中等 并发同步
1195. 交替打印字符串 中等 并发同步
1226. 哲学家进餐 中等 并发同步
1242. 多线程网页爬虫 中等 并发同步
本文作者:
本文链接: https://hgnulb.github.io/blog/2023/68965145
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!