實(shí)現(xiàn)打印26個(gè)數(shù)字和26個(gè)字母交替打印

0岁诉、面試題

實(shí)現(xiàn):第一個(gè)線程從1到26锚沸,第二個(gè)線程從A到Z,然后要讓這兩個(gè)線程做到同時(shí)運(yùn)行涕癣,交替輸出哗蜈,順序打印。

輸出結(jié)果:1A2B3C4D5E6F7G8H9I10J11K12L13M14N15O16P17Q18R19S20T21U22V23W24X25Y26Z

你有哪些玩法坠韩?

1距潘、LockSupport

public class LockSupportDemo {
    
    static Thread t1 = null, t2 = null;

    public static void main(String[] args) {
        String[] nums = new String[]{
                "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26"
        };
        String[] letters = new String[]{
                "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
        };

        t1 = new Thread(() -> {
            for (String num : nums) {
                System.out.print(num);
                LockSupport.unpark(t2);//喚醒 t2
                LockSupport.park();// t1 阻塞
            }
        }, "T1");

        t2 = new Thread(() -> {
            for (String letter : letters) {
                LockSupport.park();// t2 阻塞
                System.out.print(letter);
                LockSupport.unpark(t1);//喚醒 t1
            }
        }, "T2");

        t1.start();
        t2.start();
    }
}

2、synchronized+wait+notify

public class WaitNotifyDemo {

    static Thread t1 = null, t2 = null;


    public static void main(String[] args) {

        final Object o = new Object();

        String[] nums = new String[]{
                "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26"
        };
        String[] letters = new String[]{
                "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
        };

        t1 = new Thread(() -> {
            synchronized (o) {
                try {
                    for (String num : nums) {
                        System.out.print(num);
                        o.notify();
                        o.wait(); //阻塞 t1
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                o.notify();//必須只搁,否則無(wú)法停止程序
            }
        }, "T1");

        t2 = new Thread(() -> {
            synchronized (o) {
                try {
                    for (String letter : letters) {
                        System.out.print(letter);
                        o.notify();
                        o.wait(); //阻塞 t2
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                o.notify(); //必須音比,否則無(wú)法停止程序
            }
        }, "T2");

        t1.start();
        t2.start();
    }
}

3、ReentrantLock + 1個(gè)Condition

public class LockConditionDemo {

    static Thread t1 = null, t2 = null;

    public static void main(String[] args) {

        String[] nums = new String[]{
                "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26"
        };
        String[] letters = new String[]{
                "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
        };

        ReentrantLock lock = new ReentrantLock();

        Condition condition = lock.newCondition();

        t1 = new Thread(() -> {
            lock.lock();
            try {
                for (String num : nums) {
                    System.out.print(num);
                    condition.signal();
                    condition.await();
                }
                condition.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        }, "T1");

        t2 = new Thread(() -> {

            lock.lock();
            try {
                for (String letter : letters) {
                    System.out.print(letter);
                    condition.signal();
                    condition.await();
                }
                condition.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        }, "T2");

        t1.start();
        t2.start();
    }
}

4氢惋、ReentrantLock + 2個(gè)Condition

public class LockConditionDemo2 {

    static Thread t1 = null, t2 = null;

    public static void main(String[] args) {

        String[] nums = new String[]{
                "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26"
        };
        String[] letters = new String[]{
                "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
        };

        ReentrantLock lock = new ReentrantLock();

        Condition conditionT1 = lock.newCondition();
        Condition conditionT2 = lock.newCondition();

        t1 = new Thread(() -> {
            lock.lock();
            try {
                for (String num : nums) {
                    System.out.print(num);
                    conditionT2.signal();
                    conditionT1.await();
                }
                conditionT2.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        }, "T1");

        t2 = new Thread(() -> {

            lock.lock();
            try {
                for (String letter : letters) {
                    System.out.print(letter);
                    conditionT1.signal();
                    conditionT2.await();
                }
                conditionT1.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        }, "T2");

        t1.start();
        t2.start();
    }
}

5洞翩、自定義CAS實(shí)現(xiàn)

public class CASDemo {

    enum ReadyToRun {T1, T2}

    static volatile ReadyToRun r = ReadyToRun.T1;

    static Thread t1 = null, t2 = null;

    public static void main(String[] args) {
        String[] nums = new String[]{
                "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26"
        };
        String[] letters = new String[]{
                "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
        };

        t1 = new Thread(() -> {
            for (String num : nums) {
                while (r != ReadyToRun.T1) {
                }
                System.out.print(num);
                r = ReadyToRun.T2;
            }
        }, "T1");

        t2 = new Thread(() -> {
            for (String letter : letters) {
                while (r != ReadyToRun.T2) {
                }
                System.out.print(letter);
                r = ReadyToRun.T1;
            }
        }, "T2");

        t1.start();
        t2.start();

    }

}

6、Semaphore

public class SemaphoreDemo {

    static Thread t1 = null, t2 = null;

    private static Semaphore semaphore1 = new Semaphore(1);
    private static Semaphore semaphore2 = new Semaphore(0);

    public static void main(String[] args) {
        String[] nums = new String[]{
                "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26"
        };
        String[] letters = new String[]{
                "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
        };

        t1 = new Thread(() -> {
            try {
                for (String num : nums) {

                    semaphore1.acquire();
                    System.out.print(num);
                    semaphore2.release();

                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "T1");

        t2 = new Thread(() -> {
            try {
                for (String letter : letters) {
                    semaphore2.acquire();
                    System.out.print(letter);
                    semaphore1.release();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "T2");

        t1.start();
        t2.start();

    }

}

7焰望、BlockingQueue

public class BlockingQueueDemo {

    static BlockingQueue<String> queue1 = new ArrayBlockingQueue<>(1);
    static BlockingQueue<String> queue2 = new ArrayBlockingQueue<>(1);

    static Thread t1 = null, t2 = null;

    public static void main(String[] args) {

        String[] nums = new String[]{
                "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26"
        };
        String[] letters = new String[]{
                "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
        };

        t1 = new Thread(() -> {
            try {
                for (String num : nums) {
                    System.out.print(num);
                    queue1.put("ok");
                    queue2.take();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "T1");

        t2 = new Thread(() -> {
            try {
                for (String letter : letters) {
                    queue1.take();
                    System.out.print(letter);
                    queue2.put("ok");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "T2");

        t1.start();
        t2.start();
        
    }

}

8骚亿、TransferQueue

public class TransferQueueDemo {

    static Thread t1 = null, t2 = null;

    public static void main(String[] args) {
        String[] nums = new String[]{
                "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26"
        };
        String[] letters = new String[]{
                "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
        };

        TransferQueue<String> queue = new LinkedTransferQueue<>();

        t1 = new Thread(() -> {
            try {
                for (String num : nums) {
                    queue.transfer(num);
                    System.out.print(queue.take());
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "T1");

        t2 = new Thread(() -> {
            try {
                for (String letter : letters) {
                    System.out.print(queue.take());
                    queue.transfer(letter);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "T2");

        t1.start();
        t2.start();
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市熊赖,隨后出現(xiàn)的幾起案子来屠,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,509評(píng)論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件俱笛,死亡現(xiàn)場(chǎng)離奇詭異绣檬,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)嫂粟,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)墨缘,“玉大人星虹,你說(shuō)我怎么就攤上這事∧魉希” “怎么了宽涌?”我有些...
    開封第一講書人閱讀 163,875評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)蝶棋。 經(jīng)常有香客問(wèn)我卸亮,道長(zhǎng),這世上最難降的妖魔是什么玩裙? 我笑而不...
    開封第一講書人閱讀 58,441評(píng)論 1 293
  • 正文 為了忘掉前任兼贸,我火速辦了婚禮,結(jié)果婚禮上吃溅,老公的妹妹穿的比我還像新娘溶诞。我一直安慰自己,他們只是感情好决侈,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,488評(píng)論 6 392
  • 文/花漫 我一把揭開白布螺垢。 她就那樣靜靜地躺著,像睡著了一般赖歌。 火紅的嫁衣襯著肌膚如雪枉圃。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,365評(píng)論 1 302
  • 那天庐冯,我揣著相機(jī)與錄音孽亲,去河邊找鬼。 笑死展父,一個(gè)胖子當(dāng)著我的面吹牛墨林,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播犯祠,決...
    沈念sama閱讀 40,190評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼旭等,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了衡载?” 一聲冷哼從身側(cè)響起搔耕,我...
    開封第一講書人閱讀 39,062評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后弃榨,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體菩收,經(jīng)...
    沈念sama閱讀 45,500評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,706評(píng)論 3 335
  • 正文 我和宋清朗相戀三年鲸睛,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了娜饵。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,834評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡官辈,死狀恐怖箱舞,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情拳亿,我是刑警寧澤晴股,帶...
    沈念sama閱讀 35,559評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站肺魁,受9級(jí)特大地震影響电湘,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜鹅经,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,167評(píng)論 3 328
  • 文/蒙蒙 一寂呛、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧瘾晃,春花似錦昧谊、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,779評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至胖缤,卻和暖如春尚镰,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背哪廓。 一陣腳步聲響...
    開封第一講書人閱讀 32,912評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工狗唉, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人涡真。 一個(gè)月前我還...
    沈念sama閱讀 47,958評(píng)論 2 370
  • 正文 我出身青樓分俯,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親哆料。 傳聞我的和親對(duì)象是個(gè)殘疾皇子缸剪,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,779評(píng)論 2 354

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