zoukankan      html  css  js  c++  java
  • 使用synchronized,wait,notifyAll 实现两个线程交替打印

    package customer;
    
    /**
     * @Author lizhilong
     * @create 2020/7/6 22:22
     * @desc
     */
    public class ExchangePrint {
        public static void main(String[] args) {
    
    
            Object object = new Object();
            new Thread(()->{
                char a = 'A';
                synchronized (object){
                    for(int i=0;i<26;i++){
                        System.out.println(a);
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        a++;
                        object.notifyAll();
                        try {
                            object.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
    
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            new Thread(()->{
                synchronized (object){
                    for(int i=1;i<27;i++){
                        System.out.println(i);
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        object.notifyAll();
                        try {
                            object.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }
    }

    运行结果:

  • 相关阅读:
    746. 使用最小花费爬楼梯(动态规划题)
    91.解码方法(动态规划)
    198/213 打家劫舍(动态规划)
    5. 最长回文子串 (从今天开始刷动态规划50题)
    POJ 2142
    HDU 4686
    HDU 4767
    HDU 1757
    POJ 3613
    HDU 2157
  • 原文地址:https://www.cnblogs.com/li-zhi-long/p/13454811.html
Copyright © 2011-2022 走看看