线程间通信问题的解决

 线程间通信问题的解决:
-- wait:告诉当前线程放弃监视器并进入睡眠状态,直到其它线程进入一同监视器并且调用notify为止。
--notify:唤醒同一对象监视器中调用wait的第一个线程,这类似排队买票,一个人买完后,后面的人才可以买。

--notifyAll:唤醒同一对象监视器中调用wait的所有线程,具有最高级别的线程首先被唤醒并执行。

package xiancheng;

//synchronized的使用保证了线程间通信的同步

class P{
	String name = "李四";
	String sex = "女";
	boolean bFull = false;//取走数据位false,放入数据为true。
	
	public synchronized void set(String name,String sex){
		
		if(bFull){
			try{
				wait();
			}catch(InterruptedException x){}
		}
		
		this.name = name;
		
		try{
			Thread.sleep(10);
		}catch(Exception e){
			System.out.println(e.getMessage());
		}
		
		this.sex = sex;
		bFull = true;
		notify();
	}
	public synchronized void get(){
		
		if(!bFull){
			try{
				wait();
			}catch(InterruptedException x){}
		}
		
		System.out.println(this.name+"---->"+this.sex);
		bFull = false;
		notify();
	}
}

class Producer implements Runnable{
	P q = null;
	
	public Producer(P q){
		this.q = q;
	}
	
	public void run(){
		int i = 0;
		
		while(true){
			
			if(i==0){
				q.set("张三", "男");
			}else{
				q.set("李四", "女");
			}
			
			i = (i+1)%2;
		}
	}
}

class Customer implements Runnable{
	P q = null;
	
	public Customer(P q){
		this.q = q;
	}
	
	public void run(){
		while(true){
			q.get();
		}
	}
}

public class ThreadCommunation {

	public static void main(String[] args) {
		P q = new P();
		new Thread(new Producer(q)).start();
		new Thread(new Customer(q)).start();
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值