实现打印26个数字和26个字母交替打印

0、面试题

实现:第一个线程从1到26,第二个线程从A到Z,然后要让这两个线程做到同时运行,交替输出,顺序打印。

输出结果: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();//必须,否则无法停止程序
            }
        }, "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(); //必须,否则无法停止程序
            }
        }, "T2");

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

3、ReentrantLock + 1个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个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实现

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

推荐阅读更多精彩内容

  • 夜莺2517阅读 127,712评论 1 9
  • 版本:ios 1.2.1 亮点: 1.app角标可以实时更新天气温度或选择空气质量,建议处女座就不要选了,不然老想...
    我就是沉沉阅读 6,878评论 1 6
  • 我是黑夜里大雨纷飞的人啊 1 “又到一年六月,有人笑有人哭,有人欢乐有人忧愁,有人惊喜有人失落,有的觉得收获满满有...
    陌忘宇阅读 8,523评论 28 53
  • 兔子虽然是枚小硕 但学校的硕士四人寝不够 就被分到了博士楼里 两人一间 在学校的最西边 靠山 兔子的室友身体不好 ...
    待业的兔子阅读 2,585评论 2 9