--- waiting threads using notify paradigm wait (), notify ()

1. Wait for a thread to acquire the lock object, call the wait () method, giving up lock, into the waiting queue

2. The notification thread to acquire the lock object, call the object's notify () method

3. Wait thread receives notification from the waiting queue to the synchronization queue to enter the blocked state

4. After notification thread releases the lock, waiting for a thread to acquire a lock to continue


A code sample:

The receiving entity waits

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");

}

}

Changes modify the data open thread

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

}

}

 

 

The above is only represent the view of individual learning, we hope to provide a learning reference

Published 18 original articles · won praise 4 · Views 139

Guess you like

Origin blog.csdn.net/weixin_42081445/article/details/104846915