Java中线程基础-线程间协作-Wait,Notify/NotifyAll

等待和通知

wait()   对象上的方法

notify()/notifyAll()   对象上的方法

notify和notifyAll应该用谁?

应该尽量使用notifyAll,使用notify因为有可能发生信号丢失的的情况

 模拟快递实体类

package com.xiangxue.ch1.wn;

/**
 *
 *类说明:快递实体类
 */
public class Express {
	public final static String CITY = "ShangHai";/* 公开的final成员变量 */
    private int km;/*快递运输里程数*/
    private String site;/*快递到达地点*/

    public Express() {
    }

    public Express(int km, String site) {
        this.km = km;
        this.site = site;
    }

    /* 变化公里数,然后通知处于wait状态并需要处理公里数的线程进行业务处理*/
    public synchronized void changeKm(){
    	this.km = 101;
//    	notifyAll();//注释这里的代码对比
    	notify(); 
    	//其他的业务代码

    }

    /* 变化地点,然后通知处于wait状态并需要处理地点的线程进行业务处理*/
    public synchronized void changeSite(){
    	this.site = "BeiJing";
    	notify(); 
    }

    public synchronized void waitKm(){
    	while(this.km<=100) {
    		try {
				wait();
				System.out.println("check km thread["+Thread.currentThread().getId()
						+"] is be notifed.");
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	System.out.println("the km is"+this.km+",I will change db.");

    }

    public synchronized void waitSite(){
    	while(CITY.equals(this.site)) {
    		try {
				wait();
				System.out.println("check site thread["+Thread.currentThread().getId()
						+"] is be notifed.");
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	System.out.println("the site is"+this.site+",I will call user.");
    }
}

类说明:测试wait/notify/notifyAll

package com.xiangxue.ch1.wn;

/**
 *
 *类说明:测试wait/notify/notifyAll
 */
public class TestWN {
    private static Express express = new Express(0,Express.CITY);

    /*检查里程数变化的线程,不满足条件,线程一直等待*/
    private static class CheckKm extends Thread{
        @Override
        public void run() {
        	express.waitKm();
        }
    }

    /*检查地点变化的线程,不满足条件,线程一直等待*/
    private static class CheckSite extends Thread{
        @Override
        public void run() {
        	express.waitSite();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        for(int i=0;i<3;i++){//三个线程
            new CheckSite().start();//匿名对象
        }
        for(int i=0;i<3;i++){//里程数的变化
            new CheckKm().start();
        }
        
        Thread.sleep(1000);
        express.changeKm();//快递地点变化
    }
}

发布了132 篇原创文章 · 获赞 21 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_40993412/article/details/104141808