龙空技术网

面试官:2个线程交替打印大小写英文字母,你会怎么实现?

Java识堂 8487

前言:

此时咱们对“java打印字母”大概比较讲究,看官们都需要剖析一些“java打印字母”的相关文章。那么小编在网上网罗了一些有关“java打印字母””的相关资讯,希望姐妹们能喜欢,同学们一起来了解一下吧!

题目思路

这道题总共有2种思路

利用wait和notify函数利用volatile的可见性(volatile能保证可见性,有序性,不能保证原子性,这个一定要牢牢记住)利用Exchanger类方法一

方法二

有更好的方式欢迎大家在下方留言

放一下方法一的代码,方便大家验证

public class Solution {    private static final Object lock = new Object();    private static volatile boolean flag = true;    public static void main(String[] args) throws InterruptedException {        char[] result = new char[52];        long totalStart = System.currentTimeMillis();        Thread thread1 = new Thread(() -> {            long thread1Start = System.currentTimeMillis();            for (int i = 0; i < 26; i++) {                synchronized (lock) {                    if (flag) {                        result[i * 2] = (char)('a' + i);                        flag = false;                        lock.notify();                    } else {                        try {                            lock.wait();                        } catch (InterruptedException e) {                            e.printStackTrace();                        }                    }                }            }            long thread1Cost = System.currentTimeMillis() - thread1Start;            System.out.println("thread1Cost " + thread1Cost);        });        Thread thread2 = new Thread(() -> {            long thread2Start = System.currentTimeMillis();            for (int i = 0; i < 26; i++) {                synchronized (lock) {                    if (!flag) {                        result[i * 2 + 1] = (char)('A' + i);                        flag = true;                        lock.notify();                    } else {                        if (i != 25) {                            try {                                lock.wait();                            } catch (InterruptedException e) {                                e.printStackTrace();                            }                        }                    }                }            }            long thread2Cost = System.currentTimeMillis() - thread2Start;            System.out.println("thread2Cost " + thread2Cost);        });        thread1.start();        thread2.start();        thread1.join();        thread2.join();        // aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ        System.out.println(result);        long totalCost = System.currentTimeMillis() - totalStart;        // totalCost 119        System.out.println("totalCost " + totalCost);    }}

标签: #java打印字母