LeetCode做题解析-多线程部分(1)

题目:Foo类的三个方法会并发执行,确保first,second,third的执行顺序

解题思路:

1.信号量

每个 acquire() 方法阻塞,直到有一个许可证可以获得然后拿走一个许可证。
每个 release() 方法增加一个许可证,这可能会释放一个阻塞的 acquire() 方法。

class Foo {
   private
Semaphore seam_first_two = new Semaphore(0); // 同一时间只有0个线程能访问,意味着锁定 private Semaphore seam_two_three = new Semaphore(0); public Foo() { } public void first(Runnable printFirst) throws InterruptedException { // 没有阻塞,直接执行了
     printFirst.run();
     // 释放一个执行许可seam_first_two seam_first_two.release(); }
public void second(Runnable printSecond) throws InterruptedException { // 需要等待seam_first_two释放 seam_first_two.acquire(); printSecond.run();
     // 释放一个执行许可seam_two_three seam_two_three.release(); }
public void third(Runnable printThird) throws InterruptedException { // 需要等待seam_two_three释放 seam_two_three.acquire(); printThird.run(); } }

 

题目:两个异步的线程,同时调用Foo类,一个调用foo,一个调用bar。

输入参数n,确保程序能够显示n次的foobar

例如输入5,会输出foobarfoobarfoobarfoobarfoobar

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");
    }
  }
}

解题思路:

1.初始第一次打的时候需要确保顺序

2.通过交替打印实现

class FooBar {
    private int n;
    
    private Semaphore seam_foo = new Semaphore(0);  // 同一时间只有0个线程能访问,意味着锁定
    
    private Semaphore seam_bar = new Semaphore(0);

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

    public void foo(Runnable printFoo) throws InterruptedException {
        
        for (int i = 0; i < n; i++) {
            if(i != 0) {
                seam_foo.acquire();
            }
            printFoo.run();
            seam_bar.release();
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        
        for (int i = 0; i < n; i++) {
            seam_bar.acquire();
            printBar.run();
            seam_foo.release();
        }
    }
}

 

posted on 2019-11-01 11:54  Mrlw  阅读(318)  评论(0编辑  收藏  举报

导航