多线程并发

交替打印FooBar

方法1:信号量semaphore

class FooBar {
    private int n;

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

    Semaphore foo = new Semaphore(1);
    Semaphore bar = new Semaphore(0);

    public void foo(Runnable printFoo) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            foo.acquire();
            printFoo.run();
            bar.release();
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            bar.acquire();
            printBar.run();
            foo.release();
        }
    }
}

方法2:CyclicBarrier

public class FooBar {

    private int n;

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

    CyclicBarrier cb = new CyclicBarrier(2); // 集齐2个线程调用await时开栅放行
    volatile boolean foo = true;

    public void foo(Runnable printFoo) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            while (!foo) ;
            printFoo.run();
            foo = 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) {
            }
            printBar.run();
            foo = true;
        }
    }

}

方法3:synchronized

class FooBar {
    private int n;

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

    private boolean foo = true; // 表示当前时间应该打印foo/bar
    private Object lock = new Object();

    public void foo(Runnable printFoo) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            synchronized (lock) {
                if (!foo) {
                    lock.wait(); // 等待并且释放锁
                }
                foo = false;
                // printFoo.run() outputs "foo". Do not change or remove this line.
                printFoo.run();
                lock.notifyAll(); // 唤醒, 不释放锁; 一般唤醒代码之后,会立即退出临界区, 从而释放锁
            }
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            synchronized (lock) {
                if (foo) {
                    lock.wait(); // 等待并且释放锁
                }
                foo = true;
                // printBar.run() outputs "bar". Do not change or remove this line.
                printBar.run();
                lock.notifyAll(); // 唤醒, 不释放锁; 一般唤醒代码之后,会立即退出临界区, 从而释放锁
            }
        }
    }
}

打印零与奇偶数


semaphore信号量

class ZeroEvenOdd {
    private int n;
    private Semaphore zero = new Semaphore(1);
    private Semaphore even = new Semaphore(0);
    private Semaphore odd = 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++){
            zero.acquire();
            printNumber.accept(0);
            if(i%2==1){
                odd.release();
            }else{
                even.release();
            }
        }
    }

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

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

Lock和Condition

  • 本地测试可通过,leetcode机器超时
  • lock和condition.await/signal/signalAll,相比synchronized和wait/notify/notityAll实现类似的功能,只不过一个lock可以生成多个condition对象,所以可以精确地唤醒某个线程,synchronized关键字做不到的。
public class ZeroEvenOdd {

    // 0, 1, 0, 2, 0, 3, 0, 4, ..., 0, n
    // 1, 2, 3, 4, 5, 6, 7, 8, ..., 2n-1, 2n

    private int n;
    private volatile int count;
    private Lock lock = new ReentrantLock();
    private Condition waitForZero = lock.newCondition();
    private Condition waitForEven = lock.newCondition();
    private Condition waitForOdd = lock.newCondition();

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

    public void zero(IntConsumer printNumber) throws InterruptedException {
        while (count <= 2 * n){
            try {
                lock.lock();
                while (count % 2 == 0){
                    waitForZero.await();
                }
                if(count > 2 * n){
                    break; // 尽管while循环中count满足条件, 但是在线程唤醒之后, 其它线程改变了count值, 所以必须再加一个判断
                }
                printNumber.accept(0);
                count++;
                if(count / 2 % 2 == 1){
                    waitForOdd.signal();
                }else {
                    waitForEven.signal();
                }
            } finally {
                lock.unlock();
            }
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        while (count <= 2 * n){
            try {
                lock.lock();
                while (count % 2 == 1 || count / 2 % 2 == 1){
                    waitForEven.await();
                }
                if(count > 2 * n){
                    break;
                }
                printNumber.accept(count / 2);
                count++;
                waitForZero.signal();
            } finally {
                lock.unlock();
            }
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        while (count <= 2 * n){
            try {
                lock.lock();
                while (count % 2 == 1 || count / 2 % 2 == 0){
                    waitForOdd.await();
                }
                if(count > 2 * n){
                    break;
                }
                printNumber.accept(count / 2);
                count++;
                waitForZero.signal();
            } finally {
                lock.unlock();
            }
        }
    }
    // 本地测试
    public static void main(String[] args) {
        ZeroEvenOdd zeroEvenOdd = new ZeroEvenOdd(10);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    zeroEvenOdd.zero(value -> System.out.println(value));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    zeroEvenOdd.even(value -> System.out.println(value));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    zeroEvenOdd.odd(value -> System.out.println(value));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}

当然上面的程序稍加修改,可以只用两个condition实现,唤醒odd或者even线程的时候,可以不用精准唤醒,改用全部唤醒,因为odd和even线程都有自己的判断条件,不满足条件的线程会重新进入await(),此时另外一个正确的线程就会得到锁进行打印;

public class ZeroEvenOdd {

    // 0, 1, 0, 2, 0, 3, 0, 4, ..., 0, n
    // 1, 2, 3, 4, 5, 6, 7, 8, ..., 2n-1, 2n

    private int n;
    private volatile int count;
    private Lock lock = new ReentrantLock();
    private Condition waitForZero = lock.newCondition();
    private Condition waitForEvenOrOdd = lock.newCondition();

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

    public void zero(IntConsumer printNumber) throws InterruptedException {
        while (count <= 2 * n){
            try {
                lock.lock();
                while (count % 2 == 0){
                    waitForZero.await();
                }
                if(count > 2 * n){
                    break;
                }
                printNumber.accept(0);
                count++;
                waitForEvenOrOdd.signalAll(); // 全部唤醒, 不用精确唤醒
            } finally {
                lock.unlock();
            }
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        while (count <= 2 * n){
            try {
                lock.lock();
                while (count % 2 == 1 || count / 2 % 2 == 1){
                    waitForEvenOrOdd.await();
                }
                if(count > 2 * n){
                    break;
                }
                printNumber.accept(count / 2);
                count++;
                waitForZero.signal();
            } finally {
                lock.unlock();
            }
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        while (count <= 2 * n){
            try {
                lock.lock();
                while (count % 2 == 1 || count / 2 % 2 == 0){
                    waitForEvenOrOdd.await();
                }
                if(count > 2 * n){
                    break;
                }
                printNumber.accept(count / 2);
                count++;
                waitForZero.signal();
            } finally {
                lock.unlock();
            }
        }
    }

}

同理可用synchronized关键字加wait,notityAll实现上面的功能

public class ZeroEvenOdd {

    // 0, 1, 0, 2, 0, 3, 0, 4, ..., 0, n
    // 1, 2, 3, 4, 5, 6, 7, 8, ..., 2n-1, 2n
    private int n;
    private volatile int count;

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

    public void zero(IntConsumer printNumber) throws InterruptedException {
        while (count <= 2 * n){
            synchronized (this){
                while (count % 2 == 0){
                    this.wait();
                }
                if(count > 2 * n){
                    break;
                }
                printNumber.accept(0);
                count++;
                this.notifyAll();
            }
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        while (count <= 2 * n){
            synchronized (this){
                while (count % 2 == 1 || count / 2 % 2 == 1){
                    this.wait();
                }
                if(count > 2 * n){
                    break;
                }
                printNumber.accept(count / 2);
                count++;
                this.notifyAll();
            }
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        while (count <= 2 * n){
            synchronized (this){
                while (count % 2 == 1 || count / 2 % 2 == 0){
                    this.wait();
                }
                if(count > 2 * n){
                    break;
                }
                printNumber.accept(count / 2);
                count++;
                this.notifyAll();
            }
        }
    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,018评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,046评论 2 372
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 142,215评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,303评论 1 266
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,181评论 4 357
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,171评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,577评论 3 384
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,260评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,546评论 1 292
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,630评论 2 311
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,390评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,260评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,633评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,920评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,210评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,569评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,767评论 2 335