Problem in SCThread2.java
Opened this issue · 1 comments
Sir, In the Interthread communication problem for one producer and multiple consumer there is a problem in the code. I have fixed the problem please review
class WhiteBoard {
boolean flag[] = new boolean[10];
String text;
int numberOfStudents = 0;
int count = 0;
public WhiteBoard() {
initializeFlag();
}
public void initializeFlag() {
for (int i = 0; i < 10; i++) {
flag[i] = false;
}
}
synchronized public void changeFlag(Student s) {
String name = s.name;
int idx = Integer.parseInt(name.substring(0, 1)) - 1; // Adjust index
flag[idx] = true;
}
synchronized public boolean checkFlag(Student s) {
String name = s.name;
int idx = Integer.parseInt(name.substring(0, 1)) - 1; // Adjust index
return flag[idx];
}
public void attendance() {
numberOfStudents++;
}
synchronized public void write(String t) {
System.out.println("Teacher is Writing " + t);
while (count != 0)
try {
wait();
} catch (Exception e) {
}
text = t;
initializeFlag();
count = numberOfStudents;
notifyAll();
}
synchronized public String read() {
while (count == 0)
try {
wait();
} catch (Exception e) {
}
String t = text;
count--;
if (count == 0) {
notify();
}
return t;
}
}
class Teacher extends Thread {
WhiteBoard wb;
String notes[] = { "Java is language", "It is OOPs", "It is Platform Independent", "It supports Thread", "end" };
public Teacher(WhiteBoard w) {
wb = w;
}
public void run() {
for (int i = 0; i < notes.length; i++)
wb.write(notes[i]);
}
}
class Student extends Thread {
String name;
WhiteBoard wb;
public Student(String n, WhiteBoard w) {
name = n;
wb = w;
}
public void run() {
String text = "";
wb.attendance();
do {
if (!wb.checkFlag(this)) {
text = wb.read();
wb.changeFlag(this);
System.out.println(name + " Reading " + text);
System.out.flush();
}
} while (!text.equals("end"));
}
}
public class Main {
public static void main(String[] args) {
WhiteBoard wb = new WhiteBoard();
Teacher t = new Teacher(wb);
Student s1 = new Student("1. John", wb);
Student s2 = new Student("2. Ajay", wb);
Student s3 = new Student("3. Kloob", wb);
Student s4 = new Student("4. Smith", wb);
t.start();
s1.start();
s2.start();
s3.start();
s4.start();
}
}
code below is improved version
class WhiteBoard {
// ... (rest of the class remains the same)
synchronized public String read(Student s) {
while (count == 0) {
try {
wait();
} catch (Exception e) {
}
}
String t = text;
count--;
if (count == 0) {
notify();
}
// Set the flag for this student after reading
String name = s.name;
int idx = Integer.parseInt(name.substring(0, 1));
flag[idx] = true;
return t;
}
}
class Student extends Thread {
// ... (rest of the class remains the same)
public void run() {
String text;
wb.attendance();
do {
text = wb.read(this); // Pass the student object
System.out.println(name + " Reading " + text);
System.out.flush();
} while (!text.equals("end"));
}
}