面試官: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>


    分享到:


    相關文章: