zoukankan      html  css  js  c++  java
  • 多线程经典问题顺序打印

    开启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();
                            }
                        }
                    }
    
                }
            }
        }
    
    }
  • 相关阅读:
    素数回文 ---- 有点暴力.....
    Manacher算法 , 实例 详解 . NYOJ 最长回文
    大数处理 详解 模版
    River Crossing 简单的动态规划 .
    hdu
    产生冠军 map 的 应用 .
    MySQL的数据库备份与恢复。
    rsync的相关使用,参数设置。
    centos与mac安装python虚拟环境 virtualenvwrapper
    CentOS7安装Python3.7
  • 原文地址:https://www.cnblogs.com/songpingyi/p/9118096.html
Copyright © 2011-2022 走看看