Leetcode之多线程编程题

1116. 打印零与奇偶数

现有函数 printNumber 可以用一个整数参数调用,并输出该整数到控制台。

  • 例如,调用 printNumber(7) 将会输出 7 到控制台。

给你类 ZeroEvenOdd 的一个实例,该类中有三个函数:zeroeven 和 odd 。ZeroEvenOdd 的相同实例将会传递给三个不同线程:

  • 线程 A:调用 zero() ,只输出 0
  • 线程 B:调用 even() ,只输出偶数
  • 线程 C:调用 odd() ,只输出奇数

修改给出的类,以输出序列 "010203040506..." ,其中序列的长度必须为 2n 。

实现 ZeroEvenOdd 类:

  • ZeroEvenOdd(int n) 用数字 n 初始化对象,表示需要输出的数。
  • void zero(printNumber) 调用 printNumber 以输出一个 0 。
  • void even(printNumber) 调用printNumber 以输出偶数。
  • void odd(printNumber) 调用 printNumber 以输出奇数。

Semaphore

class ZeroEvenOdd {
    private int n;
    private Semaphore zeroSema = new Semaphore(1);
    private Semaphore oddSema = new Semaphore(0);//奇数
    private Semaphore evenSema = new Semaphore(0);//偶数

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

    public void zero(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            zeroSema.acquire();
            printNumber.accept(0);
            if (i % 2!= 0) {//奇数
                oddSema.release();
            } else {
                evenSema.release();
            }
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            if (i % 2== 0) {//偶数 打印偶数 并释放zero的线程
                evenSema.acquire();
                printNumber.accept(i);
                zeroSema.release();
            }
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            if (i % 2 != 0) {//奇数,打印奇数,并释放zero的线程
                oddSema.acquire();
                printNumber.accept(i);
                zeroSema.release();
            }
        }
    }
}

 synchronized

class ZeroEvenOdd {
    private int n;
    private final Object ob=new Object();
    private volatile int flag=0;


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

    public void zero(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            synchronized (ob){
                while (flag!=0){
                    ob.wait();
                }
                printNumber.accept(0);
                if(i%2==0)
                    flag=2;
                else
                    flag=1;
                ob.notifyAll();
            }
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            if (i % 2== 0) {//偶数 打印偶数 并释放zero的线程
                synchronized (ob){
                    while (flag!=2){
                        ob.wait();
                    }
                    printNumber.accept(i);
                    flag=0;
                    ob.notifyAll();
                }
            }
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            if (i % 2!= 0) {//偶数 打印偶数 并释放zero的线程
                synchronized (ob){
                    while (flag!=1){
                        ob.wait();
                    }
                    printNumber.accept(i);
                    flag=0;
                    ob.notifyAll();
                }
            }
        }
    }
}

CountDownLatch

class ZeroEvenOdd {
    private int n;
    private CountDownLatch countDownLatch_zero=new CountDownLatch(0);

    private CountDownLatch countDownLatch_even=new CountDownLatch(1);

    private CountDownLatch countDownLatch_odd=new CountDownLatch(1);

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

    public void zero(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            countDownLatch_zero.await();
            printNumber.accept(0);
            countDownLatch_zero=new CountDownLatch(1);
            if (i % 2!= 0) {//奇数
               countDownLatch_odd.countDown();
            } else {
                countDownLatch_even.countDown();
            }
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            if (i % 2== 0) {//偶数 打印偶数 并释放zero的线程
                countDownLatch_even.await();
                printNumber.accept(i);
                countDownLatch_even=new CountDownLatch(1);
                countDownLatch_zero.countDown();
            }
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            if (i % 2 != 0) {//奇数,打印奇数,并释放zero的线程
                countDownLatch_odd.await();
                printNumber.accept(i);
                countDownLatch_odd=new CountDownLatch(1);
                countDownLatch_zero.countDown();
            }
        }
    }
}

 Lock

class ZeroEvenOdd {
    private int n;
    private volatile int flag=0;
    Lock lock=new ReentrantLock();
    Condition condition_zero = lock.newCondition();
    Condition conditon_even = lock.newCondition();
    Condition condition_odd = lock.newCondition();


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

    public void zero(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            lock.lock();
            try{
                while (flag!=0){
                    condition_zero.await();
                }
                printNumber.accept(0);
                if(i%2==0) {
                    flag = 2;
                    conditon_even.signal();
                }
                else {
                    flag = 1;
                    condition_odd.signal();
                }
            }finally {
                lock.unlock();
            }
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            if (i % 2== 0) {//偶数 打印偶数 并释放zero的线程
                lock.lock();
                try {
                    while (flag != 2) {
                        conditon_even.await();
                    }
                    printNumber.accept(i);
                    flag = 0;
                    condition_zero.signal();
                }finally {
                    lock.unlock();
                }
                
            }
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            if (i % 2!= 0) {//偶数 打印偶数 并释放zero的线程
                lock.lock();
                try {
                    while (flag != 1) {
                        condition_odd.await();
                    }
                    printNumber.accept(i);
                    flag = 0;
                    condition_zero.signal();
                }finally {
                    lock.unlock();
                }
            }
        }
    }
}

Thread.yield

class ZeroEvenOdd {
    private int n;
    private volatile int flag=0;


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

    public void zero(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
                while (flag!=0){
                    Thread.yield();
                }
                printNumber.accept(0);
                if(i%2==0)
                    flag=2;
                else
                    flag=1;
            
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            if (i % 2== 0) {//偶数 打印偶数 并释放zero的线程
                    while (flag!=2){
                        Thread.yield();
                    }
                    printNumber.accept(i);
                    flag=0;
            }
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            if (i % 2!= 0) {//偶数 打印偶数 并释放zero的线程
                    while (flag!=1){
                       Thread.yield();
                    }
                    printNumber.accept(i);
                    flag=0;
                }
        }
    }
}

LockSupport

LockSupport类的核心方法其实就两个:park()和unpark(),其中park()方法用来阻塞当前调用线程,unpark()方法用于唤醒指定线程。 这其实和Object类的wait()和signal()方法有些类似,但是LockSupport的这两种方法从语意上讲比Object类的方法更清晰,而且可以针对指定线程进行阻塞和唤醒。
LockSupport类使用了一种名为Permit(许可)的概念来做到阻塞和唤醒线程的功能,可以把许可看成是一种(0,1)信号量(Semaphore),但与 Semaphore 不同的是,许可的累加上限是1。 初始时,permit为0,当调用unpark()方法时,线程的permit加1,当调用park()方法时,如果permit为0,则调用线程进入阻塞状态。

class ZeroEvenOdd {
    private int n;
    private volatile int flag=0;
    private ConcurrentHashMap map=new ConcurrentHashMap<>();


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

    public void zero(IntConsumer printNumber) throws InterruptedException {
        map.put("zero",Thread.currentThread());
        for (int i = 1; i <= n; i++) {
                while (flag!=0){
                    LockSupport.park();
                }
                printNumber.accept(0);
                if(i%2==0) {
                    flag = 2;
                    LockSupport.unpark(map.get("even"));
                }
                else {
                    flag = 1;
                    LockSupport.unpark(map.get("odd"));
                }

        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        map.put("even",Thread.currentThread());
        for (int i = 1; i <= n; i++) {
            if (i % 2== 0) {//偶数 打印偶数 并释放zero的线程
                    while (flag!=2){
                        LockSupport.park();
                    }
                    printNumber.accept(i);
                    flag=0;
                    LockSupport.unpark(map.get("zero"));
            }
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        map.put("odd",Thread.currentThread());
        for (int i = 1; i <= n; i++) {
            if (i % 2!= 0) {//偶数 打印偶数 并释放zero的线程
                    while (flag!=1){
                       Thread.yield();
                    }
                    printNumber.accept(i);
                    flag=0;
                    LockSupport.unpark(map.get("zero"));
            }
        }
    }
}

1195. 交替打印字符串

编写一个可以从 1 到 n 输出代表这个数字的字符串的程序,但是:

  • 如果这个数字可以被 3 整除,输出 "fizz"。
  • 如果这个数字可以被 5 整除,输出 "buzz"。
  • 如果这个数字可以同时被 3 和 5 整除,输出 "fizzbuzz"。

例如,当 n = 15,输出: 1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, 11, fizz, 13, 14, fizzbuzz

假设有这么一个类:

class FizzBuzz {
  public FizzBuzz(int n) { ... }               // constructor
  public void fizz(printFizz) { ... }          // only output "fizz"
  public void buzz(printBuzz) { ... }          // only output "buzz"
  public void fizzbuzz(printFizzBuzz) { ... }  // only output "fizzbuzz"
  public void number(printNumber) { ... }      // only output the numbers
}

请你实现一个有四个线程的多线程版  FizzBuzz, 同一个 FizzBuzz 实例会被如下四个线程使用:

  1. 线程A将调用 fizz() 来判断是否能被 3 整除,如果可以,则输出 fizz
  2. 线程B将调用 buzz() 来判断是否能被 5 整除,如果可以,则输出 buzz
  3. 线程C将调用 fizzbuzz() 来判断是否同时能被 3 和 5 整除,如果可以,则输出 fizzbuzz
  4. 线程D将调用 number() 来实现输出既不能被 3 整除也不能被 5 整除的数字。

CyclicBarrier

class FizzBuzz {
    private int n;
    private CyclicBarrier cb = new CyclicBarrier(4);

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

    // printFizz.run() outputs "fizz".
    public void fizz(Runnable printFizz) throws InterruptedException, BrokenBarrierException {
        for (int i = 1; i <= n; i++) {
            if (i % 3 == 0 && i % 5 != 0) {
                printFizz.run();
            }
            cb.await();
        }
    }

    // printBuzz.run() outputs "buzz".
    public void buzz(Runnable printBuzz) throws InterruptedException, BrokenBarrierException {
        for (int i = 1; i <= n; i++) {
            if (i % 3 != 0 && i % 5 == 0) {
                printBuzz.run();
            }
            cb.await();
        }
    }

    // printFizzBuzz.run() outputs "fizzbuzz".
    public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException, BrokenBarrierException {
        for (int i = 1; i <= n; i++) {
            if (i % 3 == 0 && i % 5 == 0) {
                printFizzBuzz.run();
            }
            cb.await();
        }
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void number(IntConsumer printNumber) throws InterruptedException, BrokenBarrierException {
        for (int i = 1; i <= n; i++) {
            if (i % 3 != 0 && i % 5 != 0) {
                printNumber.accept(i);
            }
            cb.await();
        }
    }
}

你可能感兴趣的:(并发编程和高并发实战,leetcode,算法,职场和发展)