概述
最近在leetcode上看多线程的题库,在评论区看到挺多解法,所以想整理下。
semaphore是最容易理解的
1114 按序打印
input:[1,2,3]
output:"onetwothree"
input:[1,3,2]
output:"onethreetwo"
class Foo04 {
public Semaphore sema1
= new Semaphore(0);
public Semaphore sema2 = new Semaphore(0);
public Foo04() {
}
public void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
sema1.release();//+1
}
public void second(Runnable printSecond) throws InterruptedException {
sema1.acquire();//-1
printSecond.run();
sema2.release();//+1
}
public void third(Runnable printThird) throws InterruptedException {
sema2.acquire();//-1
printThird.run();
}
}
首先因为信号量阻塞,只能first();
first()结束后,可以second()和first();
second()结束后,可以third()和first();
third()结束后,只能first()。
但为什么两个都可以的时候,选的是first()呢?猜想:1、题目对每个函数只调用一次;2、release()唤醒阻塞的线程,直接提到最高优先级。
再加一个semaphore,我能更好理解。
1115 交替打印
input:2
output:"foobarfoobar"
class FooBar06{
private int n;
public Semaphore sema_foo = new Semaphore(1);
public Semaphore sema_bar = new Semaphore(0);
public void foo(Runnable printFoo)throws InterruptedException {
for (int i = 0; i < n; i++) {
sema_foo.acquire();
printFoo.run();
sema_bar.release();
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
sema_bar.acquire();
printBar.run();
sema_foo.release();
}
}
}
1116 打印零和奇偶数
input:2
output:"0102"
class ZeroEvenOdd {
private int n;
private Semaphore semaZero = new Semaphore(1);
private Semaphore semaOdd = new Semaphore(0);
private Semaphore semaEven = 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++) {
semaZero.acquire();
printNumber.accept(0);
if(i%2==1)
semaOdd.release();
else
semaEven.release();
}
}
public void even(IntConsumer printNumber) throws InterruptedException {
for(int i=2;i<=n;i+=2) {
semaEven.acquire();
printNumber.accept(i);
semaZero.release();
}
}
public void odd(IntConsumer printNumber) throws InterruptedException {
for(int i=1;i<=n;i+=2) {
semaOdd.acquire();
printNumber.accept(i);
semaZero.release();
}
}
}
1117 H2O生成
class H2O {
private Semaphore h = new Semaphore(2);
private Semaphore o = new Semaphore(2);
public H2O() {
}
public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
h.acquire(1);
releaseHydrogen.run();
o.release(1);
}
public void oxygen(Runnable releaseOxygen) throws InterruptedException {
o.acquire(2);
releaseOxygen.run();
h.release(2);
}
}
打印出来不是固定顺序。不行了csdn怎么打字打不下去。
最后
以上就是痴情鸭子为你收集整理的多线程编程leetcode的全部内容,希望文章能够帮你解决多线程编程leetcode所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复