多線程循環輸出兩個數組(多線程實踐)

用兩個線程將兩個數組輪流輸出(數組可能不等長)。輸入a1[1,2,3,4],a2[5,6,7,8,9] 輸出1,5,2,6,3,7,4,8java

輪流輸出兩個數的實現方法有多種,最簡單的能夠採用Synchronized來同步實現,若是這是面試場合的題目的話,恐怕不是面試官想要的答案,由於同步意味着效率不高,在這給出利用volatile可見性來實現的輪流輸出的功能面試

public class Main {
    //開關
    volatile boolean sw = true;
    //判斷是否有數組已輸出完
    volatile boolean over = false;

    public static void main(String[] args) {
        int[] a1 = new int[]{1, 2, 3, 4};
        int[] a2 = new int[]{5, 6, 7, 8, 9};
        Main test = new Main();
        test.process(a1, a2);
    }

    private void process(int[] a1, int[] a2) {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < a1.length; i++) {
                while (sw != true && over == false) {
                    //自旋;能夠加睡眠時間
                }
                if (sw == true) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(a1[i]);
                    sw = false;
                }
            }
            over = true;
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < a2.length; i++) {
                while (sw != false && over == false) {
                    //自旋
                }
                if (sw == false || over == true) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(a2[i]);
                    sw = true;
                }
            }
            over = true;
        });
        t1.start();
        t2.start();
    }
相關文章
相關標籤/搜索