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

题目

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

思路

这道题总共有2种思路

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


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


    方法二


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


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

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

    <code>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);
    }
    }/<code>


    分享到:


    相關文章: