生产者消费者模型(信号灯法)

package 多线程学习;
/*
 * 生产者消费者模型之信号灯法(利用标志位解决)
 */
public class TestPC2 {
	public static void main(String[] args) {
		Question question=new Question();
		new Thread(new Teacher(question)).start();
		new Thread(new Student(question)).start();
	}
}
//生产者->老师
class Teacher implements Runnable{
	Question question;
	public Teacher(Question question) {
		this.question=question;
	}
	@Override
	public void run() {
		for(int i=0;i<20;i++) {
			if(i%2==0) {
				question.ask("你了解计算机网络吗?");
			}
			else {
				question.ask("你了解操作系统吗?");
			}
		}
		
	}
}
//消费者->学生
class Student implements Runnable{
	Question question;
	public Student(Question question) {
		this.question=question;
	}
	@Override
	public void run() {
		for(int i=0;i<20;i++) {
			question.answer();
		}
	}
}

//产品->问题
class Question{
	//老师提问,学生等待
	//学生回答,老师等待
	String content;//问题的内容
	boolean flag=true;
	
	//提问
	public synchronized void ask(String content) {
		if(!flag) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("老师提出了问题:"+content);
		//通知学生回答
		this.notifyAll();
		this.content=content;
		this.flag=!this.flag;
	}
	
	
	//回答
	public synchronized void answer() {
		if(flag) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("学生回答了问题:"+content);
		//通知老师提问
		this.notifyAll();
		this.flag=!this.flag;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值