zoukankan      html  css  js  c++  java
  • 线程交替打印奇偶

    class TestThread implements Runnable {
    private int i = 1;

    	public void run() {
    		while (true) {
    			synchronized (this) {
    				notify();
    				System.out.println(Thread.currentThread().getName() + ":" + i++);
    				try {
    					wait();
    				} catch (InterruptedException e) {
    					e.printStackTrace();
    				}
    				if (i == 101) {
    					notify();//线程2执行完输出100后,进行等待池,线程1被唤醒拿到锁从wait()后面开始执行,此时i=101,需要先把线程2从等待池唤醒再结束循环
    					break;
    				}
    			}
    		}
    	}
    }
    
    public class Test7 {
    	public static void main(String[] args) {
    		TestThread t = new TestThread();
    		Thread t1 = new Thread(t);
    		Thread t2 = new Thread(t);
    
    		t1.setName("线程1");
    		t2.setName("线程2");
    
    		t1.start();
    		//把线程2延迟一会开启,为了始终让线程1先拿到锁
    		try {
    			Thread.sleep(5);
    		} catch (InterruptedException e) {
    			e.printStackTrace();
    		}
    		t2.start();
    	}
    }
  • 相关阅读:
    List
    美团Leaf分布式ID生成策略
    单点登陆
    ElasticSearch
    Eureka
    Nginx
    UML
    Computer English
    加密
    Excel中把一列数据转换成逗号隔开的一行
  • 原文地址:https://www.cnblogs.com/mdc1771344/p/10063878.html
Copyright © 2011-2022 走看看