Java线程通讯

线程通信:
线程之间达到通信交流的效果,实现生产者消费者模式
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();
		}
	}
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值