[LeetCode] 1115. Print FooBar Alternately

本文探讨了在多线程环境中如何确保正确并发执行的方法。通过使用synchronized关键字和wait/notify机制,实现两个线程间foo和bar的交替打印,确保了线程安全和预期的输出顺序。

Suppose you are given the following code:

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

The same instance of FooBar will be passed to two different threads. Thread A will call foo() while thread B will call bar(). Modify the given program to output "foobar" n times.

 

Example 1:

Input: n = 1
Output: "foobar"
Explanation: There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar(). "foobar" is being output 1 time.

Example 2:

Input: n = 2
Output: "foobarfoobar"
Explanation: "foobar" is being output 2 times.

我们通过同步synchronized(lock())来进行阻塞操作,用isfooPrint来标记,如果满足while循环,则锁等待,不满足while循环,则进行下一步操作,进入打印程序,改写isfooPrint的值,唤醒其他进程。

class FooBar {
    private int n;
    Object lock=new Object();
    boolean isfooPrint;
    public FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {
        
        for (int i = 0; i < n; i++) {
            synchronized(lock){
                while(isfooPrint==true){
                    lock.wait();
                }
        	// printFoo.run() outputs "foo". Do not change or remove this line.
        	printFoo.run();
            isfooPrint=true;
            lock.notify();
            }
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        
        for (int i = 0; i < n; i++) {
            synchronized(lock){
                while(isfooPrint==false){
                    lock.wait();
                }
            // printBar.run() outputs "bar". Do not change or remove this line.
        	printBar.run();
            isfooPrint=false;
            lock.notify();
            }
        }
    }
}

也可以通过volatile关键字和其他锁机制进行结合,volatile关键字简介可参考:

https://blog.youkuaiyun.com/liuwenyou/article/details/100690719

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值