线程通信:
线程之间达到通信交流的效果,实现生产者消费者模式
wait() 和 notify()
线程必须在同步块里调用 wait()或者 notify(),同一对象调用操作才可以,否则会出现异常IllegalMonitorStateException
wait() 进入到对应对象的等待池中进行等待,是阻塞状态,等待唤醒,进入就绪状态,等待cpu的调度
让出cpu的资源,释放对象的锁
notify() 唤醒,唤醒某一个对象的等待池中的线程
实例:
模拟人车公用街道:
街道 信号灯 boolean
人 :ns() true
车 :we() false
public class Demo06{
public static void main(String[] args) {
Street street=new Street();
new Thread(new Person(street)).start();
new Thread(new Car(street)).start();
}
}
/*
* 街道
*/
class Street{
boolean flag=false;
//ns
public synchronized void ns(){
if(flag==false){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("人走");
flag=false;
this.notify();
}
}
//we 车 false
public synchronized void we(){
if(flag==true){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("车走");
flag=true;
this.notify();
}
}
}
class Person implements Runnable{
Street street;
public Person(Street street) {
super();
this.street = street;
}
@Override
public void run() {
while(true){
street.ns();
}
}
}
class Car implements Runnable{
Street street;
public Car(Street street) {
super();
this.street = street;
}
@Override
public void run() {
while(true){
street.we();
}
}
}