线程通信
1)、wait()
线程等待,会让出对象的锁,让出cpu的资源,会进入到对象的等待池中,等待被唤醒—>阻塞状态
2)、notify()
唤醒具有可以运行的资源
3)、信号灯案例
package thread.communication;
public class Thread01 {
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;
/*
* 南北 人走true
*/
public synchronized void ns(){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("人走。。。。。");
flag=false;
this.notify();
}
}
/*
* 东西 车走
*/
public synchronized void we(){
if(flag==true){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("车走");
flag=true;
this.notify();
}
}
//人
class Person implements Runnable{
//共享资源
Street street=null;
public Person(Street street){
this.street=street;
}
@Override
public void run() {
while(true){
street.ns();
}
}
}
//车
class Car implements Runnable{
//共享资源
Street street=null;
public Car(Street street) {
super();
this.street = street;
}
@Override
public void run() {
while(true){
street.we();
}
}
}
注: 多线程之间共享数据的处理|存储,使用wait() 和 notify()必须在一个安全同步的环境下。如果没有在同步环境下会抛出异常:IllegalMonitorStateException