Java實現兩個線程交替打印問題

線程1負責打印a,b,c,d

線程2負責打印1,2,3,4

要求控制檯中輸出的內容爲 a1b2c3d4

package com.sdmjhca.springBootDemo.countdownlatch;


/**
 * @author JHMI on 2017/8/28.
 */
public class TestMain {
    static final Object object = new Object();
    public static void main(String[] args) throws InterruptedException {

        new Thread(new Runnable() {
            String a[] = {"a","b","c","d"};
            @Override
            public void run() {
                for(int i=0;i< 4 ;i++){
                    synchronized (object){
                        System.out.println("線程a 開始執行");
                        object.notify();
                        try {
                            System.out.println("線程a 開始等待");
                            object.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("線程a 繼續執行");
                        System.out.println(a[i]);
                        System.out.println("線程a 執行結束");
                        object.notify();
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
            int a[] = {1,2,3,4};
            @Override
            public void run() {
                for(int i=0;i<4;i++){
                    synchronized (object){
                        System.out.println("線程1 開始執行");
                        object.notify();
                        try {
                            System.out.println("線程1 開始等待");
                            object.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("線程1  繼續執行");
                        System.out.println(a[i]);
                        System.out.println("線程1  執行結束");
                    }
                }

            }
        }).start();
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章