多線程并發(fā)

交替打印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個線程調(diào)用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; // 表示當(dāng)前時間應(yīng)該打印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(); // 喚醒, 不釋放鎖; 一般喚醒代碼之后,會立即退出臨界區(qū), 從而釋放鎖
            }
        }
    }

    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(); // 喚醒, 不釋放鎖; 一般喚醒代碼之后刊殉,會立即退出臨界區(qū), 從而釋放鎖
            }
        }
    }
}

打印零與奇偶數(shù)


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機(jī)器超時
  • lock和condition.await/signal/signalAll,相比synchronized和wait/notify/notityAll實(shí)現(xiàn)類似的功能记焊,只不過一個lock可以生成多個condition對象逸月,所以可以精確地喚醒某個線程,synchronized關(guān)鍵字做不到的遍膜。
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循環(huán)中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();
    }

}

當(dāng)然上面的程序稍加修改碗硬,可以只用兩個condition實(shí)現(xiàn)瓤湘,喚醒odd或者even線程的時候,可以不用精準(zhǔn)喚醒恩尾,改用全部喚醒弛说,因?yàn)閛dd和even線程都有自己的判斷條件,不滿足條件的線程會重新進(jìn)入await()翰意,此時另外一個正確的線程就會得到鎖進(jìn)行打幽救恕;

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關(guān)鍵字加wait,notityAll實(shí)現(xiàn)上面的功能

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();
            }
        }
    }

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末冀偶,一起剝皮案震驚了整個濱河市醒第,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌进鸠,老刑警劉巖稠曼,帶你破解...
    沈念sama閱讀 212,718評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異堤如,居然都是意外死亡蒲列,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,683評論 3 385
  • 文/潘曉璐 我一進(jìn)店門搀罢,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人侥猩,你說我怎么就攤上這事榔至。” “怎么了欺劳?”我有些...
    開封第一講書人閱讀 158,207評論 0 348
  • 文/不壞的土叔 我叫張陵唧取,是天一觀的道長。 經(jīng)常有香客問我划提,道長枫弟,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,755評論 1 284
  • 正文 為了忘掉前任鹏往,我火速辦了婚禮淡诗,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘伊履。我一直安慰自己韩容,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,862評論 6 386
  • 文/花漫 我一把揭開白布唐瀑。 她就那樣靜靜地躺著群凶,像睡著了一般。 火紅的嫁衣襯著肌膚如雪哄辣。 梳的紋絲不亂的頭發(fā)上请梢,一...
    開封第一講書人閱讀 50,050評論 1 291
  • 那天赠尾,我揣著相機(jī)與錄音,去河邊找鬼毅弧。 笑死气嫁,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的形真。 我是一名探鬼主播杉编,決...
    沈念sama閱讀 39,136評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼咆霜!你這毒婦竟也來了邓馒?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,882評論 0 268
  • 序言:老撾萬榮一對情侶失蹤蛾坯,失蹤者是張志新(化名)和其女友劉穎光酣,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體脉课,經(jīng)...
    沈念sama閱讀 44,330評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡救军,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,651評論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了倘零。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片唱遭。...
    茶點(diǎn)故事閱讀 38,789評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖呈驶,靈堂內(nèi)的尸體忽然破棺而出拷泽,到底是詐尸還是另有隱情,我是刑警寧澤袖瞻,帶...
    沈念sama閱讀 34,477評論 4 333
  • 正文 年R本政府宣布司致,位于F島的核電站,受9級特大地震影響聋迎,放射性物質(zhì)發(fā)生泄漏脂矫。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,135評論 3 317
  • 文/蒙蒙 一霉晕、第九天 我趴在偏房一處隱蔽的房頂上張望庭再。 院中可真熱鬧,春花似錦娄昆、人聲如沸佩微。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,864評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽哺眯。三九已至,卻和暖如春扒俯,著一層夾襖步出監(jiān)牢的瞬間奶卓,已是汗流浹背一疯。 一陣腳步聲響...
    開封第一講書人閱讀 32,099評論 1 267
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留夺姑,地道東北人墩邀。 一個月前我還...
    沈念sama閱讀 46,598評論 2 362
  • 正文 我出身青樓,卻偏偏與公主長得像盏浙,于是被迫代替她去往敵國和親眉睹。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,697評論 2 351