多線程-按序打印的4種寫法

題目描述:

我們提供了一個(gè)類:

public class Foo {

? public void one() { print("one"); }

? public void two() { print("two"); }

? public void three() { print("three"); }

}

三個(gè)不同的線程將會(huì)共用一個(gè)?Foo?實(shí)例。

線程 A 將會(huì)調(diào)用 one() 方法

線程 B 將會(huì)調(diào)用?two() 方法

線程 C 將會(huì)調(diào)用 three() 方法

請(qǐng)?jiān)O(shè)計(jì)修改程序颓芭,以確保 two() 方法在 one() 方法之后被執(zhí)行醋粟,three() 方法在 two() 方法之后被執(zhí)行绑雄。

示例 1:

輸入: [1,2,3]

輸出: "onetwothree"

解釋:

有三個(gè)線程會(huì)被異步啟動(dòng)梆靖。

輸入 [1,2,3] 表示線程 A 將會(huì)調(diào)用 one() 方法捏雌,線程 B 將會(huì)調(diào)用 two() 方法盛险,線程 C 將會(huì)調(diào)用 three() 方法妓柜。

正確的輸出是 "onetwothree"拌倍。

示例 2:

輸入: [1,3,2]

輸出: "onetwothree"

解釋:

輸入 [1,3,2] 表示線程 A 將會(huì)調(diào)用 one() 方法赂鲤,線程 B 將會(huì)調(diào)用 three() 方法,線程 C 將會(huì)調(diào)用 two() 方法柱恤。

正確的輸出是 "onetwothree"数初。

解法1:利用鎖、成員變量來(lái)控制順序梗顺。

first方法直接打印one泡孩,并設(shè)置flag = 1,并喚醒其他所有線程寺谤。

second方法 如果flag != 1 那么輪詢仑鸥,并等待。當(dāng)first方法執(zhí)行完后变屁,那么flag = 1眼俊,此時(shí)second會(huì)執(zhí)行while塊之后的,即打印two敞贡,并設(shè)置flag = 2泵琳。如first執(zhí)行完后,third方法先執(zhí)行誊役,因此時(shí)flag =1,那么third方法會(huì)一直在輪詢获列。

third方法在second執(zhí)行完后,flag = 2蛔垢,并喚醒其他所有線程击孩,此時(shí)處于wait狀態(tài)的只有third,因此,在second執(zhí)行完后即會(huì)執(zhí)行third方法鹏漆。

class Foo {

? ? private? Object lock =? new Object();

? ? private int flag = 0;

? ? volatile int count = 1;

? ? public Foo() {

? ? }

? ? public void first(Runnable printFirst) throws InterruptedException {

? ? ? ? printFirst.run();

? ? ? ? count++;

? ? ? ? // printFirst.run() outputs "first". Do not change or remove this line.

? ? }

? ? public void second(Runnable printSecond) throws InterruptedException {

? ? ? ? while(count != 2);

? ? ? ? printSecond.run();

? ? ? ? count++;

? ? ? ? // printSecond.run() outputs "second". Do not change or remove this line.

? ? }

? ? public void third(Runnable printThird) throws InterruptedException {

? ? ? ? while(count != 3);

? ? ? ? ? printThird.run();

? ? ? ? // printThird.run() outputs "third". Do not change or remove this line.

? ? }

}

解法2:利用volatile變量

class Foo {

? ? volatile int count = 1;

? ? public Foo() {

? ? }

? ? public void first(Runnable printFirst) throws InterruptedException {

? ? ? ? printFirst.run();

? ? ? ? count++;

? ? ? ? // printFirst.run() outputs "first". Do not change or remove this line.

? ? }

? ? public void second(Runnable printSecond) throws InterruptedException {

? ? ? ? while(count != 2);

? ? ? ? printSecond.run();

? ? ? ? count++;

? ? ? ? // printSecond.run() outputs "second". Do not change or remove this line.

? ? }

? ? public void third(Runnable printThird) throws InterruptedException {

? ? ? ? while(count != 3);

? ? ? ? ? printThird.run();

? ? ? ? ? count = 1;

? ? ? ?// printThird.run() outputs "third". Do not change or remove this line.

? ? }

}

解法3:利用CountDownLatch巩梢,CountDownLatch是java.util.concurrent包下面的一個(gè)工具類创泄,可以用來(lái)協(xié)調(diào)多個(gè)線程之間的同步,或者說起到線程之間的通信(而不是用作互斥的作用)括蝠。 它可以允許一個(gè)或者多個(gè)線程等待其他線程完成操作鞠抑。

簡(jiǎn)單點(diǎn)說,直到CountDownLatch里面計(jì)數(shù)為0才執(zhí)行所有線程忌警。

首先初始化兩個(gè)數(shù)量均為1的計(jì)數(shù)器

first方法搁拙,在執(zhí)行cdla.countDown();之后 cdla 計(jì)數(shù)為0。

second方法法绵,cdla.await(); 如果cdla里計(jì)數(shù)不為0箕速,那么會(huì)一直阻塞在此,直到cdla計(jì)數(shù)為0朋譬,即first方法執(zhí)行完之后盐茎,才會(huì)通過。此時(shí)再執(zhí)行cdlb.countDown();徙赢,cdlb計(jì)數(shù)為0字柠。

third方法cdlb.await();如果cdlb里計(jì)數(shù)不為0,那么會(huì)一直阻塞在此犀忱,直到cdlb計(jì)數(shù)為0,即second方法執(zhí)行完之后募谎。

class Foo {

? ? private CountDownLatch a;

? ? private CountDownLatch b;

? ? public Foo() {

? ? ? ? a = new CountDownLatch(1);

? ? ? ? b = new CountDownLatch(1);

? ? }

? ? public void first(Runnable printFirst) throws InterruptedException {

? ? ? ? printFirst.run();

? ? ? ? a.countDown();

? ? ? ? // printFirst.run() outputs "first". Do not change or remove this line.

? ? }

? ? public void second(Runnable printSecond) throws InterruptedException {

? ? ? ? a.await();

? ? ? ? printSecond.run();

? ? ? ? b.countDown();

? ? ? ? // printSecond.run() outputs "second". Do not change or remove this line.

? ? }

? ? public void third(Runnable printThird) throws InterruptedException {

? ? ? ? ? b.await();

? ? ? ? ? printThird.run();

? ? ? ? // printThird.run() outputs "third". Do not change or remove this line.

? ? }

}


解法4:利用信號(hào)量Semaphore

Semaphore 是 synchronized 的加強(qiáng)版,作用是控制線程的并發(fā)數(shù)量阴汇。

如果我們?cè)O(shè)置Semaphore 里初始值為0数冬,就是一開始使線程阻塞從而完成其他執(zhí)行。

原理和CountDownLatch 差不多搀庶。

first方法直接釋放(初始值為0拐纱,是可以釋放的)。

second方法在最開始會(huì)獲取spa哥倔,只有first方法執(zhí)行完之后秸架,才能在此處獲取到,即只有first執(zhí)行完之后才會(huì)執(zhí)行second咆蒿。并釋放spb东抹。

third方法在最開始會(huì)獲取spb,spb釋放是在second執(zhí)行完之后沃测,因此只有在second執(zhí)行完之后才會(huì)執(zhí)行third缭黔。

class Foo {

? ? private Semaphore a;

? ? private Semaphore b;

? ? public Foo() {

? ? ? ? a = new Semaphore(0);

? ? ? ? b = new Semaphore(0);

? ? }

? ? public void first(Runnable printFirst) throws InterruptedException {

? ? ? ? printFirst.run();

? ? ? ? a.release();

? ? ? ? // printFirst.run() outputs "first". Do not change or remove this line.

? ? }

? ? public void second(Runnable printSecond) throws InterruptedException {

? ? ? ? a.acquire();

? ? ? ? printSecond.run();

? ? ? ? b.release();

? ? ? ? // printSecond.run() outputs "second". Do not change or remove this line.

? ? }

? ? public void third(Runnable printThird) throws InterruptedException {

? ? ? ? ? b.acquire();

? ? ? ? ? printThird.run();

? ? ? ? // printThird.run() outputs "third". Do not change or remove this line.

? ? }

}


測(cè)試代碼:

public static void main(String[] args) {

Foo foo =new Foo();

? ? for (int i =0; i <8; i++) {

ExecutorService executor = Executors.newFixedThreadPool(3);

? ? ? ? executor.submit(() -> {

try {

foo.first(() -> {

System.out.println("one");

? ? ? ? ? ? ? ? });

? ? ? ? ? ? }catch (InterruptedException e) {

e.printStackTrace();

? ? ? ? ? ? }

});

? ? ? ? executor.submit(() -> {

try {

foo.second(() -> {

System.out.println("two");

? ? ? ? ? ? ? ? });

? ? ? ? ? ? }catch (InterruptedException e) {

e.printStackTrace();

? ? ? ? ? ? }

});

? ? ? ? executor.submit(() -> {

try {

foo.third(() -> {

System.out.println("three");

? ? ? ? ? ? ? ? });

? ? ? ? ? ? }catch (InterruptedException e) {

e.printStackTrace();

? ? ? ? ? ? }

});

? ? ? ? executor.isShutdown();

? ? }

}




個(gè)人座右銘:主動(dòng)? 行動(dòng)? 思考? ?反省? 總結(jié)


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市蒂破,隨后出現(xiàn)的幾起案子馏谨,更是在濱河造成了極大的恐慌,老刑警劉巖附迷,帶你破解...
    沈念sama閱讀 218,607評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件惧互,死亡現(xiàn)場(chǎng)離奇詭異哎媚,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)喊儡,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,239評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門拨与,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人艾猜,你說我怎么就攤上這事截珍。” “怎么了箩朴?”我有些...
    開封第一講書人閱讀 164,960評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)秋度。 經(jīng)常有香客問我炸庞,道長(zhǎng),這世上最難降的妖魔是什么荚斯? 我笑而不...
    開封第一講書人閱讀 58,750評(píng)論 1 294
  • 正文 為了忘掉前任埠居,我火速辦了婚禮,結(jié)果婚禮上事期,老公的妹妹穿的比我還像新娘滥壕。我一直安慰自己,他們只是感情好兽泣,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,764評(píng)論 6 392
  • 文/花漫 我一把揭開白布绎橘。 她就那樣靜靜地躺著,像睡著了一般唠倦。 火紅的嫁衣襯著肌膚如雪称鳞。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,604評(píng)論 1 305
  • 那天稠鼻,我揣著相機(jī)與錄音冈止,去河邊找鬼。 笑死候齿,一個(gè)胖子當(dāng)著我的面吹牛熙暴,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播慌盯,決...
    沈念sama閱讀 40,347評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼周霉,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了润匙?” 一聲冷哼從身側(cè)響起诗眨,我...
    開封第一講書人閱讀 39,253評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎孕讳,沒想到半個(gè)月后匠楚,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體巍膘,經(jīng)...
    沈念sama閱讀 45,702評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,893評(píng)論 3 336
  • 正文 我和宋清朗相戀三年芋簿,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了峡懈。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,015評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡与斤,死狀恐怖肪康,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情撩穿,我是刑警寧澤磷支,帶...
    沈念sama閱讀 35,734評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站食寡,受9級(jí)特大地震影響雾狈,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜抵皱,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,352評(píng)論 3 330
  • 文/蒙蒙 一善榛、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧呻畸,春花似錦移盆、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,934評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至绞愚,卻和暖如春剑鞍,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背爽醋。 一陣腳步聲響...
    開封第一講書人閱讀 33,052評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工蚁署, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人蚂四。 一個(gè)月前我還...
    沈念sama閱讀 48,216評(píng)論 3 371
  • 正文 我出身青樓光戈,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親遂赠。 傳聞我的和親對(duì)象是個(gè)殘疾皇子久妆,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,969評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • 本文主要講了java中多線程的使用方法、線程同步跷睦、線程數(shù)據(jù)傳遞筷弦、線程狀態(tài)及相應(yīng)的一些線程函數(shù)用法、概述等。 首先講...
    李欣陽(yáng)閱讀 2,456評(píng)論 1 15
  • Java多線程學(xué)習(xí) [-] 一擴(kuò)展javalangThread類 二實(shí)現(xiàn)javalangRunnable接口 三T...
    影馳閱讀 2,959評(píng)論 1 18
  • JUC 原創(chuàng)者:文思烂琴,感謝尚硅谷爹殊,資料來(lái)源于尚硅谷 目錄: 1、volatile關(guān)鍵字與內(nèi)存可見性 2奸绷、原子變量與...
    文思li閱讀 2,316評(píng)論 0 1
  • 先看幾個(gè)概念:線程:進(jìn)程中負(fù)責(zé)程序執(zhí)行的執(zhí)行單元号醉。一個(gè)進(jìn)程中至少有一個(gè)線程反症。多線程:解決多任務(wù)同時(shí)執(zhí)行的需求,合理...
    yeying12321閱讀 543評(píng)論 0 0
  • 接下來(lái)介紹比synchronized功能上更豐富的關(guān)鍵字:重入鎖 靈活性:public class Reentra...
    innoyiya閱讀 349評(píng)論 0 1