SteR9
28-04-2006, 23:05
Ragazzi sto studiando un pò i thread in java, in particolare la loro sincronizzazione. Quello che voglio è creare 2 threads che eseguono una operazione per uno, una dietro l'altra. 
Io pensavo di eseguire un thread metterlo in wait e svegliare l'altro.
Ho creato queste 3 classi:
public class oggetti {
boolean read_state = false;
boolean write_state = false;
	
public synchronized void read() throws InterruptedException {
System.out.println("Lettore:");
notifyAll();
while(read_state != true)
wait();
}
	
public synchronized void write() throws InterruptedException {
System.out.println("invio:");
notifyAll();
while(write_state != true)
wait();
}
	
public void setReadState(boolean s){
read_state = s;
}
	
public void setWriteState(boolean s){
write_state = s;
}
}
  
public class thread_reader implements Runnable {
public void run() {
oggetti o = new oggetti();
try {
while (true) {
o.read();
o.setWriteState(true);
o.setReadState(false);
}
} catch (InterruptedException e) {
}
}
}
 
public class thread_writer implements Runnable {
public void run() {
oggetti o = new oggetti();
try {
while (true) {
o.write();
o.setWriteState(false);
o.setReadState(true);
}
} catch (InterruptedException e) {
}
}
}
 
il programma parte e i thread stampano una volta soltanto il messaggio, dopo è come se rimanessero sempre in wait. E' sbagliato il metodo che ho usato?
Io pensavo di eseguire un thread metterlo in wait e svegliare l'altro.
Ho creato queste 3 classi:
public class oggetti {
boolean read_state = false;
boolean write_state = false;
public synchronized void read() throws InterruptedException {
System.out.println("Lettore:");
notifyAll();
while(read_state != true)
wait();
}
public synchronized void write() throws InterruptedException {
System.out.println("invio:");
notifyAll();
while(write_state != true)
wait();
}
public void setReadState(boolean s){
read_state = s;
}
public void setWriteState(boolean s){
write_state = s;
}
}
public class thread_reader implements Runnable {
public void run() {
oggetti o = new oggetti();
try {
while (true) {
o.read();
o.setWriteState(true);
o.setReadState(false);
}
} catch (InterruptedException e) {
}
}
}
public class thread_writer implements Runnable {
public void run() {
oggetti o = new oggetti();
try {
while (true) {
o.write();
o.setWriteState(false);
o.setReadState(true);
}
} catch (InterruptedException e) {
}
}
}
il programma parte e i thread stampano una volta soltanto il messaggio, dopo è come se rimanessero sempre in wait. E' sbagliato il metodo che ho usato?