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;
}
}
生产者消费者模型(信号灯法)
最新推荐文章于 2022-03-04 15:47:21 发布