多线程经典问题顺序打印

开启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();
                        }
                    }
                }

            }
        }
    }

}

 

posted @ 2018-05-31 18:00  songpingyi  阅读(4107)  评论(0编辑  收藏  举报