力扣多线程练习----交替打印FooBar---打印零与奇偶数

交替打印FooBar---打印零与奇偶数


题目


两个不同的线程将会共用一个 FooBar 实例。其中一个线程将会调用 foo() 方法,另一个线程将会调用 bar() 方法。

请设计修改程序,以确保 “foobar” 被输出 n 次。
在这里插入图片描述

Semaphore

代码

import java.util.concurrent.Semaphore;

public class FooBar {
    private int n;

    public FooBar(int n) {
        this.n = n;
    }
    Semaphore semaphoreFoo=new Semaphore(1);
    Semaphore semaphoreBar=new Semaphore(0);
    public void foo(Runnable printFoo) throws InterruptedException {

        for (int i = 0; i < n; i++) {

            semaphoreFoo.acquire();
            printFoo.run();
            semaphoreBar.release();
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {

        for (int i = 0; i < n; i++) {

            semaphoreBar.acquire();
            printBar.run();
            semaphoreFoo.release();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        FooBar fooBar=new FooBar(10);
        new Thread(()->{
            try {
                fooBar.foo(new PrintFoo());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(()->{
            try {
                fooBar.bar(new PrintFar());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

    }

}
class PrintFoo implements Runnable{

    @Override
    public void run() {
        System.out.print("foo");
    }
}
class PrintFar implements Runnable{

    @Override
    public void run() {
        System.out.print("bar");
    }
}

Lock公平锁

public class FooBar {
    private int n;

    public FooBar(int n) {
        this.n = n;
    }
    Lock lock=new ReentrantLock(true);
    static volatile boolean flag=true;
    public void foo(Runnable printFoo) throws InterruptedException {

        for (int i = 0; i < n; ) {
            lock.lock();
            try {
                if(flag){
                    printFoo.run();
                    i++;
                    flag=false;
                }
            }finally {
                lock.unlock();
            }
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {

        for (int i = 0; i < n; ) {
            lock.lock();
            try {
                if(!flag){
                    printBar.run();
                    i++;
                    flag=true;
                }
            }finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        FooBar fooBar=new FooBar(10);
        new Thread(()->{
            try {
                fooBar.foo(new PrintFoo());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(()->{
            try {
                fooBar.bar(new PrintFar());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

    }

}
class PrintFoo implements Runnable{

    @Override
    public void run() {
        System.out.print("foo");
    }
}
class PrintFar implements Runnable{

    @Override
    public void run() {
        System.out.print("bar");
    }
}

打印零与奇偶数

题目

在这里插入图片描述

代码

public class ZeroEvenOdd {
    private int n;

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

    Semaphore zeros=new Semaphore(1);
    Semaphore odds=new Semaphore(0);
    Semaphore evens=new Semaphore(0);

    //线程 A 将调用 zero(),它只输出 0 。
    //线程 B 将调用 even(),它只输出偶数。
    //线程 C 将调用 odd(),它只输出奇数。
    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        int i=0;
        while(i<n){
            zeros.acquire();
            printNumber.accept(0);

            if((i+2)%2==0){
                odds.release();
            }else{
                evens.release();
            }
            i++;
        }
    }
    //打印偶数
    public void even(IntConsumer printNumber) throws InterruptedException {
        int i=0;
        while(i<n/2){
            evens.acquire();
            printNumber.accept(i*2+2);
            i++;
            zeros.release();
        }
    }
    //打印奇数
    public void odd(IntConsumer printNumber) throws InterruptedException {
        int i=0;
        while(i<(n+1)/2){
            odds.acquire();
            printNumber.accept(i*2+1);
            i++;
            zeros.release();
        }
    }

    public static void main(String[] args) {
        ZeroEvenOdd zeroEvenOdd = new ZeroEvenOdd(5);
        new Thread(()->{
            try {
                zeroEvenOdd.zero(value -> {
                    System.out.print(value);
                });
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(()->{
            try {
                zeroEvenOdd.even(value -> {
                    System.out.print(value);
                });
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(()->{
            try {
                zeroEvenOdd.odd(value -> {
                    System.out.print(value);
                });
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值