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();//快递地点变化
}
}
以上内容仅代表个人学习的见解,希望可以为大家提供一个学习参考