线程通信

线程通信

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值