微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

多线程等待和通知模式例子wait()和notifyAll()应用

public class Express {

    public final static String CITY = "ShangHai";
    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();


        //其他的业务代码
    }

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

    public synchronized void waitKm(){
        while(this.km<=100) {
            try {
                wait();
                System.out.println("check km thread["+Thread.currentThread().getId()
                        +"] is waiting to be notified.");
            } catch (InterruptedException e) {
                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 waiting to be notified.");
            } catch (InterruptedException e) {
                e.printstacktrace();
            }
        }
        System.out.println("the site is"+this.site+",I will call user.");
    }
}

 

public class TestWaitAndNotify {

    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();//快递地点变化
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐