• 两个线程,一个线程打印1到52,一个线程打印A到Z,打印顺序是12A34B……5152Z


    题目

    两个线程,一个线程打印1到52,一个线程打印A到Z,打印顺序是12A34B……5152Z

    代码实现

    public class ThreadTest {
    	
    	public static void main(String[] args){
    		
    		Foo tt = new Foo();
    		
    		new Thread(()->{
    			synchronized (tt) {
    				for (int i = 1; i <= 52; i++) {
    					while(tt.x != 1){
    						try {
    							tt.notify();
    							tt.wait();
    						} catch (Exception e) {
    						
    						}
    					}
    					System.out.println(i);
    					if(i % 2 == 0){
    						tt.x = 2;
    					}
    				}
    				//是为了唤醒最后一次打印Z
    				tt.notify();
    			}
    		},"线程1").start();
    		
    		new Thread(()->{
    			synchronized (tt) {
    				for (int i = 'A'; i <= 'Z'; i++) {
    					while(tt.x != 2){
    						try {
    							tt.notify();
    							tt.wait();
    						} catch (Exception e) {
    						
    						}
    					}
    					System.out.println((char)i);
    					tt.x = 1;
    				}
    			}
    		},"线程2").start();
    	}
    }
    
    class Foo{
    	public int x = 1;
    }
    
  • 相关阅读:
    sql 计算auc
    tf.app.flags
    transformer
    python 直连 hive
    rnn 详解
    yolov3
    记学习react-native
    html5横、竖屏状态 以及禁止横屏
    图片懒加载
    npm安装的时候报-4048
  • 原文地址:https://www.cnblogs.com/kaka-qiqi/p/14831213.html
Copyright © 2020-2023  润新知