多线程-leetcode1115-交替打印

leetcode-1115 交替打印

两个线程用一个对象实例,这两个线程各自执行一个方法,该实例的两个方法交替执行
1114题种通过while()循环,造成资源的浪费,并且执行缓慢,本题通过可重入锁和condition
本题也可以通过两个信号量Semaphore来实现并发控制

class FooBar {
    private int n;
    ReentrantLock lock = new ReentrantLock();
    Condition fooCondition = lock.newCondition();
    Condition barCondition = lock.newCondition();
    boolean flag = true;

    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){
                fooCondition.await();
            }
            // printFoo.run() outputs "foo". Do not change or remove this line.
            printFoo.run();
            flag = false;
            barCondition.signal();
            lock.unlock();
        }
    }

    public void bar(Runnable printBar) throws InterruptedException{

        for(int i = 0; i < n; i++){
            lock.lock();
            if(flag){
                barCondition.await();
            }
            // printBar.run() outputs "bar". Do not change or remove this line.
            printBar.run();
            flag = true;
            fooCondition.signal();
            lock.unlock();

        }
    }
}
java高并发编程 文章被收录于专栏

介绍一些关于java并发编程的原理,并对并发编程实例进行实现,也会涉及一些关于秒杀高并发系统实践

全部评论

相关推荐

流浪的神仙:无恶意,算法一般好像都得9硕才能干算法太卷啦
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务