LeetCode 1115 交替打印FooBar

显式锁真好用╮( ̄▽ ̄")╭,以下是尚硅谷老师讲JUC时用的课件,我给粘过来了,说明一下Lock

  • 在 Java 5.0 之前,协调共享对象的访问时可以使用的机制只有synchronized 和 volatile 。Java 5.0 后增加了一些新的机制,但并不是一种替代内置锁的方法,而是当内置锁不适用时,作为一种可选择的高级功能。
  • ReentrantLock 实现了 Lock 接口,并提供了与synchronized 相同的互斥性和内存可见性。但相较于synchronized 提供了更高的处理锁的灵活性。

继续用这个做题吧。

题目要求

package multithreading;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MyFooBar {
	public static void main(String[] args) {
		FooBar fb = new FooBar(5);	//为了测试简单,给定值5
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					fb.foo(new Runnable() {
						@Override
						public void run() {
							System.out.println("foo");
						}
					});
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
			}
		}).start();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					fb.bar(new Runnable() {
						@Override
						public void run() {
							System.out.println("bar");
						}
					});
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
			}
		}).start();
	}
}
class FooBar {
    private int n;
    private Lock lock = new ReentrantLock();
    private int flag = 1;
    private Condition condition1 = lock.newCondition(); 
    private Condition condition2 = lock.newCondition(); 
    
    public FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {
        
        for (int i = 0; i < n; i++) {
        	lock.lock();
        	if(flag != 1) {
            	condition1.await();
            }
            // printFoo.run() outputs "foo". Do not change or remove this line.
            printFoo.run();
            flag = 2;
            condition2.signal();
            lock.unlock();
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        
        for (int i = 0; i < n; i++) {
        	lock.lock();
        	if(flag != 2) {
            	condition2.await();
            }
            // printBar.run() outputs "bar". Do not change or remove this line.
        	printBar.run();
            flag = 1;
            condition1.signal();
            lock.unlock();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值