• 两个线程交替打印1到100


    package com.zs.thread;
    
    import java.util.concurrent.TimeUnit;
    
    public class SumThread {
    	
    	public void one() throws InterruptedException{
    		synchronized (this) {
    			boolean flag = true;
    			
    			while (flag) {
    				
    				for(int i = 1; i <= 99;i += 2){
    					System.out.println(i);
    					
    					if(i==99){
    						flag = false;
    						this.notify();
    						break;
    					}
    					this.notify();
    					this.wait();
    				}
    			}
    		}
    	}	
    		
    	public void two() throws InterruptedException{
    			synchronized (this) {
    				boolean flag = true;
    				
    				while (flag) {
    					
    					for(int i = 2; i <= 100;i += 2){
    						System.out.println(i);
    						
    						if(i==100){
    							flag = false;
    							this.notify();
    							break;
    						}
    						this.notify();
    						this.wait();
    					}
    				}
    			}
    		}
    		
    		
    	
    	public static void main(String[] args) throws Exception {
    		SumThread sumThread = new SumThread();
    		
    		new Thread(()->{
    			try {
    				sumThread.one();
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    		}).start();
    		
    		TimeUnit.SECONDS.sleep(1);
    		
    		new Thread(()->{
    			try {
    				sumThread.two();
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    		}).start();
    	}
    }
    
    
  • 相关阅读:
    浏览器市场份额
    GDB gdb 调试
    tcp基础
    TCP加速方式
    windows10 CTCP
    大延时情况tcp和udp测试
    XAMPP与ISS在80端口冲突问题
    space transport protocols
    win10电脑搭建网站
    如何让nginx显示文件夹目录
  • 原文地址:https://www.cnblogs.com/leihuazhe/p/7898563.html
Copyright © 2020-2023  润新知