LeetCode 1115. 交替打印FooBar (wait + notify、BlockingQuque)

1115. 交替打印FooBar


一道典型的 一个生产者、一个消费者的场景

wait + notify

class FooBar {
    private int n;

    boolean available = false;

    public FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            synchronized (this) {
                if (available) {
                    this.wait();
                }
                printFoo.run();
                this.notify();
                this.available = !this.available;
            }
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            synchronized (this) {
                if (!available) {
                    this.wait();
                }
                printBar.run();
                this.notify();
                this.available = !this.available;
            }
        }
    }
}

BlockingQueue

import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;

class FooBar {
    private int n;

    BlockingQueue<Integer> q1 = new LinkedBlockingQueue<>();
    BlockingQueue<Integer> q2 = new LinkedBlockingQueue<>();

    public FooBar(int n) {
        this.n = n;
        q1.offer(0);
    }

    public void foo(Runnable printFoo) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            q1.take();
            printFoo.run();
            q2.put(0);
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            q2.take();
            printBar.run();
            q1.put(0);
        }
    }
}

SynchronousQueue

顺序要注意一下。

class FooBar {
    private SynchronousQueue<Integer> queue1 = new SynchronousQueue<>(), queue2 = new SynchronousQueue<>();
    private int n;

    public FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {
        
        for (int i = 0; i < n; i++) {
        	printFoo.run();
            queue2.put(0);
            queue1.take();
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        
        for (int i = 0; i < n; i++) {
            queue2.take();
        	printBar.run();
            queue1.put(0);
        }
    }
}

此题使用 信号量似乎也是很合适的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值