如何解决在应该被通知之前通知线程,一种生产者消费者问题白板问题,找不到合适的算法JAVA
所以,我正在尝试编写一个程序,其中老师有一块白板来写行,学生应该复制它。老师只允许在所有学生完成输入的行后在白板上写另一行(基本上老师一次只能写一行)。这是预期的输出:
显示器已交给白板...
class WhiteBoard{
String text;
int noOfStudents=0;
boolean flag=true; //If teacher writes "end" on the white board the program terminates
int c=0; //if c=0 teacher writes (Counter)
Scanner sc=new Scanner(System.in);
synchronized public void write(){ //Teacher uses this function
while (c != 0) {
try {
wait();
} catch (Exception e) {
}
}
System.out.print("\nWrite on White Board: ");
text=sc.nextLine();
c=1; //To allow the students to copy the line
if(text.equals("end")){
flag=false;
}
notifyAll();
}
synchronized String read(String name){ //Student uses this fucntion
while (c == 0) {
try {
wait();
} catch (Exception e) {
}
}
//I think the error is here:
c++;
c=(c%(noOfStudents+1)); //
if(c==0){ //I know this is totally wrong but i cant find a way to put a successful lock
notify();
}
return name+" Has finished copying: "+text;
}
}
我得到的输出:
但是如果我在教师和学生类的 run() 方法中调用 sleep() 输出结果很好。 剩下的代码如下:
class Teacher extends Thread{
WhiteBoard w;
Teacher(WhiteBoard w){
this.w=w;
}
public void run(){
while(w.flag) {
w.write();
//If i write sleep here then i get the desired output only
//try{Thread.sleep(100);}catch(Exception e){}
}
}
}
class Student extends Thread{
WhiteBoard w;
String name;
Student(String name,WhiteBoard w){
this.w=w;
this.name=name;
w.noOfStudents++;
}
public void run(){
do{
//If i write sleep here then i get the desired output only
//try{Thread.sleep(100);}catch(Exception e){}
System.out.println(w.read(name));
}while(w.flag);
}
}
public class Main {
public static void main(String[] args) {
// write your code here
WhiteBoard wh=new WhiteBoard();
Teacher t=new Teacher(wh);
Student s1=new Student("Ram",wh);
Student s2=new Student("Shyam",wh);
Student s3=new Student("Hari",wh);
t.start();
s1.start();
s2.start();
s3.start();
}
}
你能帮我找到同步写入和读取方法的算法吗?
解决方法
学生线程之间存在对白板访问权限的争用。线程调度器可以调度同一个线程依次从白板上读取,而不是按照您希望的方式轮流与其他学生线程。睡眠会导致每个学生线程暂停,让另一个学生线程从白板上读取。这允许每个线程从白板上读取老师写的每条消息。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。