目录

T の weblog

X

【LeetCode刷题】1115. 交替打印FooBar

题目

我们提供一个类:

class FooBar {
  public void foo() {
    for (int i = 0; i < n; i++) {
      print("foo");
    }
  }

  public void bar() {
    for (int i = 0; i < n; i++) {
      print("bar");
    }
  }
}

两个不同的线程将会共用一个 FooBar 实例。其中一个线程将会调用 foo() 方法,另一个线程将会调用 bar() 方法。

请设计修改程序,以确保 "foobar" 被输出 n 次。

示例 1:

输入: n = 1
输出: "foobar"
解释: 这里有两个线程被异步启动。其中一个调用 foo() 方法, 另一个调用 bar() 方法,"foobar" 将被输出一次。

示例 2:

输入: n = 2
输出: "foobarfoobar"
解释: "foobar" 将被输出两次。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/print-foobar-alternately
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法:

采用之前生成H2O的办法实现

如果按照上次生成H2O的办法去做,是不行的,为什么呢?

package run.runnable.leetcode;

import java.util.concurrent.*;

public class AlternatePrint {

    private int n;
    private BlockingQueue<String> f = new ArrayBlockingQueue<>(1);
    private BlockingQueue<String> b = new ArrayBlockingQueue<>(1);
    private CyclicBarrier cyclicBarrier = new CyclicBarrier(2);

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

    public void foo(Runnable printFoo) throws InterruptedException, BrokenBarrierException {

        for (int i = 0; i < n; i++) {
            f.put("f");
            // printFoo.run() outputs "foo". Do not change or remove this line.
            printFoo.run();
            cyclicBarrier.await();
            f.take();
        }
    }

    public void bar(Runnable printBar) throws InterruptedException, BrokenBarrierException {

        for (int i = 0; i < n; i++) {
            b.put("b");
            // printBar.run() outputs "bar". Do not change or remove this line.
            printBar.run();
            cyclicBarrier.await();
            b.take();
        }
    }

    public static void main(String[] args) throws InterruptedException, BrokenBarrierException {

        AlternatePrint alternatePrint = new AlternatePrint(100);
        Thread th1 = new Thread(()->{
            System.out.print("foo");
        });
        Thread th2 = new Thread(()->{
            System.out.print("bar");
        });
        new Thread(()->{
            try {
                alternatePrint.foo(th1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(()->{
            try {
                alternatePrint.bar(th2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }).start();

    }

}

输出结果

foobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarfoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoobarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoofoobarbarfoo

输出的结果并不都是foobar,还有barfoo

所以这里我们还需要保证foo在bar之前进行输出。

所以,可以在其中加一个CountDownLatch,代码如下

package run.runnable.leetcode;

import java.util.concurrent.*;

public class AlternatePrint {

    private int n;
    private BlockingQueue<String> f = new ArrayBlockingQueue<>(1);
    private BlockingQueue<String> b = new ArrayBlockingQueue<>(1);
    private CyclicBarrier cyclicBarrier = new CyclicBarrier(2);
    private CountDownLatch countDownLatch = new CountDownLatch(1);

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

    public void foo(Runnable printFoo)  {

        for (int i = 0; i < n; i++) {
            try {
                f.put("f");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            countDownLatch.countDown();
            // printFoo.run() outputs "foo". Do not change or remove this line.
            printFoo.run();
            try {
                cyclicBarrier.await();
                f.take();
            } catch (BrokenBarrierException | InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

    public void bar(Runnable printBar) {

        for (int i = 0; i < n; i++) {
            try {
                b.put("b");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // printBar.run() outputs "bar". Do not change or remove this line.
            printBar.run();
            countDownLatch = new CountDownLatch(1);
            try {
                cyclicBarrier.await();
                b.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }

        }
    }

    public static void main(String[] args) throws InterruptedException, BrokenBarrierException {

        AlternatePrint alternatePrint = new AlternatePrint(100);
        Thread th1 = new Thread(()->{
            System.out.print("foo");
        });
        Thread th2 = new Thread(()->{
            System.out.print("bar");
        });
        new Thread(()->{
            alternatePrint.foo(th1);
        }).start();
        new Thread(()->{
            alternatePrint.bar(th2);
        }).start();

    }

}

输出

image.png
虽然完成了任务,但是效率并不怎么好
image.png

改良一下,删除队列,其实也可以实现

package run.runnable.leetcode;

import java.util.concurrent.*;

public class AlternatePrint {

    private int n;
    private CyclicBarrier cyclicBarrier = new CyclicBarrier(2);
    private CountDownLatch countDownLatch = new CountDownLatch(1);

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

    public void foo(Runnable printFoo)  {

        for (int i = 0; i < n; i++) {
            countDownLatch.countDown();
            // printFoo.run() outputs "foo". Do not change or remove this line.
            printFoo.run();
            try {
                cyclicBarrier.await();
            } catch (BrokenBarrierException | InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

    public void bar(Runnable printBar) {

        for (int i = 0; i < n; i++) {
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // printBar.run() outputs "bar". Do not change or remove this line.
            printBar.run();
            countDownLatch = new CountDownLatch(1);
            try {
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }

        }
    }

    public static void main(String[] args) throws InterruptedException, BrokenBarrierException {

        AlternatePrint alternatePrint = new AlternatePrint(100);
        Thread th1 = new Thread(()->{
            System.out.print("foo");
        });
        Thread th2 = new Thread(()->{
            System.out.print("bar");
        });
        new Thread(()->{
            alternatePrint.foo(th1);
        }).start();
        new Thread(()->{
            alternatePrint.bar(th2);
        }).start();

    }

}

这次效率有所提升
image.png

更简单的办法

在leetcode上看到的

一、分析题意:

1、(问题一)首先是两条线程异步调用,两条线程不能确定他们谁先谁有,也就是有序性
2、(问题二)在线程执行的时候需要保证foo每次循环都在bar前,这样的话肯定是需要线程不能往下执行。
3、 解决以上两个问题基本就解决了,所以联想到以下两个关键字解决,volatile 可见性且有序,yield()让线程暂停。

二、首先解释两个用到的关键字 volatile yield();

yield :暂停当前正在执行的线程对象,yield()只是使当前线程重新回到可执行状态,所以执行yield()的线程有可能在进入到可执 行状态后马上又被执行。
volatile:保证了不同线程对这个变量进行操作时的可见性,即一个线程修改了某个变量的值,这新值对其他线程来说是立即可见的。 (实现可见性)
禁止进行指令重排序。(实现有序性)
volatile 只能保证对单次读/写的原子性。i++ 这种操作不能保证原子性。

三、解题过程

循环执行两次,首先确认目前的flag的状态以确保一定是foo执行(为了解决问题一,关键词volatile),来判断是否往下执 行,如果不是那么让当前不往下执行(关键词yield())
优化:可以在 yield() 时增限制,避免无限的循环。

代码

class FooBar {
    
    private int n;
    private volatile int flag = 0;
	public FooBar(int n) {
		this.n = n;
	}

	public void foo(Runnable printFoo) throws InterruptedException {
         for (int i = 0; i < n; i++) {
			while(flag != 0){
				Thread.yield();
			}
			printFoo.run();
			flag = 1;
		}
	}

	public void bar(Runnable printBar) throws InterruptedException {
        for (int i = 0; i < n; i++) {
			while(flag != 1){
				Thread.yield();
			}
			printBar.run();
			flag = 0;
		}
	}
    
}

作者:hellowzqk
链接:https://leetcode-cn.com/problems/print-foobar-alternately/solution/wu-suo-qie-zui-jian-dan-zui-rong-yi-li-jie-de-shi-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


标题:【LeetCode刷题】1115. 交替打印FooBar
作者:MingGH
地址:https://runnable.run/articles/2020/01/19/1579426203131.html