多線程經典問題順序打印


開啟3個線程,這3個線程的ID分別為A、B、C,
 * 每個線程將自己的ID在屏幕上打印10遍,要求輸出結果必須按ABC的順序顯示;
 * 如:ABCABC….依次遞推。

序輸出ABC用synchronized的代碼實現

/**
 * create by spy on 2018/5/31
 */
public class ThreadShunXuPrint {
    public static void main(String[] args) {
        Object obj = new Object();
        for (int i = 0; i < 3; i++) {
            new Thread(new printThread(obj, "" + (char) (i + 65), i, 121)).start();
        }
    }
    static class printThread implements Runnable {
        private static Object object;//線程加鎖對象
        private String threadName;//線程名稱要打印的字母
        private int threadId;//線程指定的下標ID
        private static int count = 0;//已打印次數
        private Integer totalCount = 0;//總打印次數


        public printThread(Object object, String threadName, int threadId, Integer totalCount) {
            this.object = object;
            this.threadName = threadName;
            this.threadId = threadId;
            this.totalCount = totalCount;
        }

        @Override
        public void run() {
            synchronized (object) {//判斷該資源是否正在被使用
                while (count < totalCount) {
                    if (count % 3 == threadId) {
                        //判斷當前已打印次取余線程數相等打印否則等待
                        System.out.println(threadName);
                        count++;
                        object.notifyAll();
                    } else {
                        try {
                            object.wait();
                        } catch (Exception e) {
                            System.out.println("線程" + threadName + "打斷了!");
                            e.printStackTrace();
                        }
                    }
                }

            }
        }
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM