线程运用---等待通知的范式wait()、notify()

1.等待线程获取到对象的锁,调用wait()方法,放弃锁,进入等待队列

2.通知线程获取到对象的锁,调用对象的notify()方法

3.等待线程接受到通知,从等待队列移到同步队列,进入阻塞状态

4.通知线程释放锁后,等待线程获取到锁继续执行


以下为代码示例:

接收等待的实体

public class Express {

public final static StringCITY ="BeiJing";

private int km;/*运输里程数*/

private Stringsite;/*到达地点*/

public Express() {

}

public Express(int km, String site) {

this.km = km;

this.site = site;

}

/* 变化公里数,然后通知处于wait状态并需要处理公里数的线程进行业务处理*/

public synchronized void changeKm(){

this.km =101;

notify();

}

/* 变化地点,然后通知处于wait状态并需要处理地点的线程进行业务处理*/

public  synchronized  void changeSite(){

this.site ="BeiJing";

notifyAll();

}

/*线程等待公里的变化*/

public synchronized void waitKm(){

while(this.km<100){

try {

wait();

System.out.println("Check Site thread[" +Thread.currentThread().getId()+"] is be notified");

}catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.println("the Km is "+this.km+",I will change db");

}

/*线程等待目的地的变化*/

public synchronized void waitSite(){

while(this.site.equals(CITY)){//快递到达目的地

try {

wait();

System.out.println("Check Site thread["+Thread.currentThread().getId()+"] is be notified");

}catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.println("the site is "+this.site+",I will call user");

}

}

开启线程修改数据的变化

public class TestWN {

private static Expressexpress =new Express(0,Express.CITY);

/*检查里程数变化的线程,不满足条件,线程一直等待*/

private static class CheckKmextends Thread{

@Override

public void run() {

express.waitKm();

}

}

/*检查地点变化的线程,不满足条件,线程一直等待*/

private static class CheckSiteextends 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();//快递地点变化

}

}

 

 

以上内容仅代表个人学习的见解,希望可以为大家提供一个学习参考

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一名技术极客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值