LeetCode 多线程练习2(1116. 打印零与奇偶数 / H2O 生成)

多线程练习2

1116. 打印零与奇偶数

题目描述

假设有这么一个类:

class ZeroEvenOdd {
  public ZeroEvenOdd(int n) { ... }      // 构造函数
  public void zero(printNumber) { ... }  // 仅打印出 0
  public void even(printNumber) { ... }  // 仅打印出 偶数
  public void odd(printNumber) { ... }   // 仅打印出 奇数
}

相同的一个 ZeroEvenOdd 类实例将会传递给三个不同的线程:

  1. 线程 A 将调用 zero(),它只输出 0 。
  2. 线程 B 将调用 even(),它只输出偶数。
  3. 线程 C 将调用 odd(),它只输出奇数。

每个线程都有一个 printNumber 方法来输出一个整数。请修改给出的代码以输出整数序列 010203040506… ,其中序列的长度必须为 2n。

示例 1:

输入:n = 2
输出:“0102”
说明:三条线程异步执行,其中一个调用 zero(),另一个线程调用 even(),最后一个线程调用odd()。正确的输出为 “0102”。

示例 2:

输入:n = 5
输出:“0102030405”

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/print-zero-even-odd
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

信号量

信号量简单好用,真香
超过85

class ZeroEvenOdd {
    private int n;
    
    private Semaphore ling = new Semaphore(1);
    private Semaphore ji = new Semaphore(0);
    private Semaphore ou = new Semaphore(0);

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

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        for(int i = 1; i <= n; i++){
            ling.acquire();
            printNumber.accept(0);
            if(i % 2 == 1)
                ji.release();
            else
                ou.release();
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        for(int i = 2; i <= n; i += 2){
            ou.acquire();
            printNumber.accept(i);
            ling.release();
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        for(int i = 1; i <= n; i += 2){
            ji.acquire();
            printNumber.accept(i);
            ling.release();
        }
    }
}

volatile+ Thread.yield()

85

class ZeroEvenOdd {
    private int n;
    
    private volatile boolean ling = true;
    private volatile boolean ou = false;
    private volatile boolean ji = false;

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

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        for(int i = 1; i <= n;){
            if(!ling)
                Thread.yield();
            else{
                printNumber.accept(0);
                ling = false;
                if(i % 2 == 1)
                    ji = true;
                else    
                    ou = true;
                i++;
            }
        }    
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        for(int i = 2; i <= n;){
            if(!ou)
                Thread.yield();
            else{
                printNumber.accept(i);
                ou = false;
                ling = true;
                i += 2;
            }
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        for(int i = 1; i <= n;){
            if(!ji)
                Thread.yield();
            else{
                printNumber.accept(i);
                ji = false;
                ling = true;
                i += 2;
            }
        }
    }
}

原子类控制 + Thread.yield()

class ZeroEvenOdd {
    private int n;
    
    private AtomicInteger ji = new AtomicInteger(0);
    private AtomicInteger ou = new AtomicInteger(0);

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

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        for(int i = 1; i <= n; i++){
            while(ji.get() != 0 || ou.get() != 0)
                Thread.yield();
            printNumber.accept(0);
            if(i % 2 == 1)
                ji.incrementAndGet();
            else
                ou.incrementAndGet();
        }    
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        for(int i = 2; i <= n; i += 2){
            while(ou.get() != 1)
                Thread.yield();
            printNumber.accept(i);
            ou.set(0);
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        for(int i = 1; i <= n; i += 2){
            while(ji.get() != 1)
                Thread.yield();
            printNumber.accept(i);
            ji.set(0);
        }
    }
}

ReentrantLock + Condition

85

class ZeroEvenOdd {
    private int n;

    private volatile int num = 0;
    private Lock lock = new ReentrantLock();
    private Condition ling = lock.newCondition();
    private Condition ou = lock.newCondition();
    private Condition ji = lock.newCondition();


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

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        for(int i = 1; i <= n; i++){
            lock.lock();
            try{
                while(num != 0){
                    ling.await();
                }
                printNumber.accept(0);
                if(i % 2 == 1){
                    ji.signal();
                    num = 1;
                }
                else{
                    ou.signal();
                    num = 2;
                }
            } catch(Exception e){
                e.printStackTrace();
            } finally{
                lock.unlock();
            }
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        for(int i = 2; i <= n; i += 2){
            lock.lock();
            try{
                while(num != 2){
                    ou.await();
                }
                printNumber.accept(i);
                ling.signal();
                num = 0;
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                lock.unlock();
            }
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        for(int i = 1; i <= n; i += 2){
            lock.lock();
            try{
                while(num != 1){
                    ji.await();
                }
                printNumber.accept(i);
                ling.signal();
                num = 0;
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                lock.unlock();
            }
        }
    }
}

CountDownLatch

100

class ZeroEvenOdd {
    private int n;
    
    CountDownLatch ling = new CountDownLatch(0);
    CountDownLatch ji = new CountDownLatch(1);
    CountDownLatch ou = new CountDownLatch(1);

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

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        for(int i = 1; i <= n; i++){
            //变为0执行
            ling.await();
            printNumber.accept(0);
            ling = new CountDownLatch(1);
            if(i % 2 == 1)
                ji.countDown();
            else
                ou.countDown();
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        for(int i = 2; i <= n; i += 2){
            ou.await();
            printNumber.accept(i);
            ou = new CountDownLatch(1);
            ling.countDown();
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        for(int i = 1; i <= n; i += 2){
            ji.await();
            printNumber.accept(i);
            ji = new CountDownLatch(1);
            ling.countDown();
        }
    }
}

SynchronousQueue

52

class ZeroEvenOdd {
    private int n;
    
    BlockingQueue<Integer> synzero = new SynchronousQueue<>();
    BlockingQueue<Integer> synodd = new SynchronousQueue<>();
    BlockingQueue<Integer> syneven = new SynchronousQueue<>();

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

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        for(int i = 1; i <= n; i++){
            printNumber.accept(0);
            if(i % 2 == 1){
                //给奇数队列放东西
                synodd.put(1);
            }else
                syneven.put(1);
            //从0队列取东西,如果没有,阻塞
            synzero.take();
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        for(int i = 2; i <= n; i += 2){
            syneven.take();
            printNumber.accept(i);
            synzero.put(1);
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        for(int i = 1; i <= n; i += 2){
            synodd.take();
            printNumber.accept(i);
            synzero.put(1);
        }
    }
}

BlockingQueue

100

class ZeroEvenOdd {
    private int n;
    
    private BlockingQueue<Integer> ling = new LinkedBlockingQueue<>();
    private BlockingQueue<Integer> ji = new LinkedBlockingQueue<>();
    private BlockingQueue<Integer> ou = new LinkedBlockingQueue<>();

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

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        for(int i = 1; i <= n; i++){
            printNumber.accept(0);
            if(i % 2 == 1)
                ji.put(1);
            else
                ou.put(1);
            ling.take();
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        for(int i = 2; i <= n; i += 2){
            ou.take();
            printNumber.accept(i);
            ling.put(1);
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        for(int i = 1; i <= n; i += 2){
            ji.take();
            printNumber.accept(i);
            ling.put(1);
        }
    }
}

LockSupport

class ZeroEvenOdd {
    private int n;
    
    private Map<String, Thread> map = new HashMap<>();
    private volatile int num = 0;
    public ZeroEvenOdd(int n) {
        this.n = n;
    }

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

    public void even(IntConsumer printNumber) throws InterruptedException {
        map.put("even", Thread.currentThread());
        for(int i = 2; i <= n; i += 2){
            while(num != 2)
                LockSupport.park();
            printNumber.accept(i);
            num = 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 += 2){
            while(num != 1)
                LockSupport.park();
            printNumber.accept(i);
            num = 0;
            LockSupport.unpark(map.get("zero"));
        }
    }
}

1117. H2O 生成

题目描述

现在有两种线程,氧 oxygen 和氢 hydrogen,你的目标是组织这两种线程来产生水分子。

存在一个屏障(barrier)使得每个线程必须等候直到一个完整水分子能够被产生出来。

氢和氧线程会被分别给予 releaseHydrogen 和 releaseOxygen 方法来允许它们突破屏障。

这些线程应该三三成组突破屏障并能立即组合产生一个水分子。

你必须保证产生一个水分子所需线程的结合必须发生在下一个水分子产生之前。

换句话说:

如果一个氧线程到达屏障时没有氢线程到达,它必须等候直到两个氢线程到达。
如果一个氢线程到达屏障时没有其它线程到达,它必须等候直到一个氧线程和另一个氢线程到达。
书写满足这些限制条件的氢、氧线程同步代码。

示例 1:

输入: “HOH”
输出: “HHO”
解释: “HOH” 和 “OHH” 依然都是有效解。

示例 2:

输入: “OOHHHH”
输出: “HHOHHO”
解释: “HOHHHO”, “OHHHHO”, “HHOHOH”, “HOHHOH”, “OHHHOH”, “HHOOHH”, “HOHOHH” 和 “OHHOHH” 依然都是有效解。

提示:

输入字符串的总长将会是 3n, 1 ≤ n ≤ 50;
输入字符串中的 “H” 总数将会是 2n 。
输入字符串中的 “O” 总数将会是 n 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/building-h2o
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

信号量

学到了信号量,可以一次获取释放多个资源,默认是获取一个资源:

class H2O {
    
    private Semaphore h = new Semaphore(2);
    private Semaphore o = new Semaphore(0);

    public H2O() {
        
    }

    public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
        h.acquire();
        // releaseHydrogen.run() outputs "H". Do not change or remove this line.
        releaseHydrogen.run();
        o.release();
    }

    public void oxygen(Runnable releaseOxygen) throws InterruptedException {
        //当释放两个o时,才会产生一个氧气
        o.acquire(2);   
        // releaseOxygen.run() outputs "O". Do not change or remove this line.
		releaseOxygen.run();
        //释放两个h
        h.release(2);
    }
}

volatile+ Thread.yield() 和 原子类+Thread.yield()

不太懂怎么写,一直写不对
我觉得是因为每次加1的变化可能被其他线程所打断,导致产生问题
这道题应该是用那种能控制每个线程执行几次的方法来实现

ReentrantLock + Condition

94
我刚开始写的时候,写的是siganl,超时了;换成siganlAll,就过了
一个变量标记:

class H2O {
    
    private Lock lock = new ReentrantLock();
    private Condition h = lock.newCondition();
    private Condition o = lock.newCondition();
    private volatile int numh = 2;

    public H2O() {
        
    }

    public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
        lock.lock();
        try{
            while(numh == 0)
                h.await();
            // releaseHydrogen.run() outputs "H". Do not change or remove this line.
            releaseHydrogen.run();
            numh--;
            if(numh == 0)
                o.signalAll();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            lock.unlock();
        }
    }

    public void oxygen(Runnable releaseOxygen) throws InterruptedException {
        lock.lock();
        try{
            while(numh != 0)
                o.await();
            // releaseOxygen.run() outputs "O". Do not change or remove this line.
		    releaseOxygen.run();
            numh = 2;
            h.signalAll();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            lock.unlock();
        }
        
    }
}

两个变量标记:

class H2O {
    
    private Lock lock = new ReentrantLock();
    private Condition h = lock.newCondition();
    private Condition o = lock.newCondition();
    private volatile int numh = 2;
    private volatile int numo = 1;

    public H2O() {
        
    }

    public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
        lock.lock();
        try{
            while(numh == 0)
                h.await();
            // releaseHydrogen.run() outputs "H". Do not change or remove this line.
            numh--;
            if(numh == 0 && numo == 0){
                numh = 2;
                numo = 1;
            }
            releaseHydrogen.run();
            o.signalAll();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            lock.unlock();
        }
    }

    public void oxygen(Runnable releaseOxygen) throws InterruptedException {
        lock.lock();
        try{
            while(numo == 0)
                o.await();
            numo--;
            if(numh == 0 && numo == 0){
                numh = 2;
                numo = 1;
            }
            // releaseOxygen.run() outputs "O". Do not change or remove this line.
		    releaseOxygen.run();
            h.signalAll();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            lock.unlock();
        }
        
    }
}

CountDownLatch

同样的问题,不会写

信号量 + Semaphore+CyclicBarrier

94
这个方法就相当于创建了一个3个线程的栅栏,只有当三个线程都走到栅栏处的时候才能继续执行
而控制三个线程用了信号量,只有产生了两个H和一个O才能走到栅栏处

class H2O {

    private Semaphore h = new Semaphore(2);
    private Semaphore o = new Semaphore(1);
    //栅栏里三个线程
    private CyclicBarrier cb = new CyclicBarrier(3);
    
    public H2O() {
        
    }

    public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
		h.acquire();
        try{
            cb.await();		//线程调用 await() 表示自己已经到达栅栏
        }catch(BrokenBarrierException e){
            e.printStackTrace();
        }
        // releaseHydrogen.run() outputs "H". Do not change or remove this line.
        releaseHydrogen.run();
        h.release();
    }

    public void oxygen(Runnable releaseOxygen) throws InterruptedException {
        o.acquire();
        try{
            cb.await();
        }catch(BrokenBarrierException e){
            e.printStackTrace();
        }
        // releaseOxygen.run() outputs "O". Do not change or remove this line.
		releaseOxygen.run();
        o.release();
    }
}

synchronized

94
每次只能执行一个线程,如果h不为0就生产氢气,为0就生产氧气

class H2O {

    private volatile int h = 2;
    private Object lock = new Object();

    public H2O() {
        
    }

    public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
        synchronized(lock){
            while(h == 0)
                lock.wait();
            // releaseHydrogen.run() outputs "H". Do not change or remove this line.
            releaseHydrogen.run();
            h--;
            lock.notifyAll();
        }
    }

    public void oxygen(Runnable releaseOxygen) throws InterruptedException {
        synchronized(lock){
            while(h != 0)
                lock.wait();
            // releaseOxygen.run() outputs "O". Do not change or remove this line.
		    releaseOxygen.run();
            h = 2;
            lock.notifyAll();
        }
    }
}

BlockingQueue

用add报错,Thrown exception java.lang.IllegalStateException: Queue full;
用put可以过,put满了会等待
两者区别:
在这里插入图片描述

class H2O {
    private volatile int count = 0;
    private BlockingQueue<Integer> h = new LinkedBlockingQueue<>(2);
    private BlockingQueue<Integer> o = new LinkedBlockingQueue<>(1);

    public H2O() {
        
    }

    public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
        h.put(1);
        // releaseHydrogen.run() outputs "H". Do not change or remove this line.
        releaseHydrogen.run();
        count++;
        if(count == 3){
            count = 0;
            h.clear();
            o.clear();
        }
    }

    public void oxygen(Runnable releaseOxygen) throws InterruptedException {
        o.put(1);
        // releaseOxygen.run() outputs "O". Do not change or remove this line.
		releaseOxygen.run();
        count++;
        if(count == 3){
            count = 0;
            h.clear();
            o.clear();
        }
    }
}

LockSupport

这个方法的每个线程的许可证只有一张,生产H要两个,所以好像不太行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值