多线程LeetCode 1115. 交替打印FooBar Java代码

题目

https://leetcode-cn.com/problems/print-foobar-alternately/
在这里插入图片描述

Semaphore

class FooBar {
    private int n;
    Semaphore s1=new Semaphore(0);
    Semaphore s2=new Semaphore(1);
    public FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {
        
        for (int i = 0; i < n; i++) {
            s2.acquire();
        	// printFoo.run() outputs "foo". Do not change or remove this line.
        	printFoo.run();
            s1.release();
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        
        for (int i = 0; i < n; i++) {
            s1.acquire();
            // printBar.run() outputs "bar". Do not change or remove this line.
        	printBar.run();
            s2.release();
        }
    }
}

无锁

这玩意提交超时了

class FooBar {
    private int n;
    volatile boolean ff=true;
    public FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {
        
        for (int i = 0; i < n; ) {
            if(ff){
        	    // printFoo.run() outputs "foo". Do not change or remove this line.
        	    printFoo.run();
                i++;
                ff=false;
            }
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        
        for (int i = 0; i < n;) {
            if(!ff){
                // printBar.run() outputs "bar". Do not change or remove this line.
        	    printBar.run();
                i++;
                ff=true;
            }
        }
    }
}

CyclicBarrier

它让一组线程到达一个屏障(也可以叫同步点)时被阻塞,直到最后一个线程到达屏障时,屏障才会开门,所有被屏障拦截的线程才会继续运行。
每个线程调用await方法告诉CyclicBarrier我已经到达了屏障,然后当前线程被阻塞。

class FooBar {
    private int n;

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

    CyclicBarrier cb = new CyclicBarrier(2);
    volatile boolean fin = true;

    public void foo(Runnable printFoo) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            while(!fin){};
            printFoo.run();
            fin = false;
            try {
		        cb.await();//第一个线程通过栅栏
	        } catch (BrokenBarrierException e) {
	        }
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            try {
		        cb.await();//第二个线程通过栅栏
	        } catch (BrokenBarrierException e) {
	        }
	        //已有两个线程通过栅栏,可以允许下述代码了。并且栅栏count重置为2。
            printBar.run();
            fin = true;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值