pranzu
06-05-2006, 16:21
Riporto un esempio tratto da Thinking in Java e semplificato.
class SimpleSemaphore extends Thread {
public static volatile int semaphore = 0;
public SimpleSemaphore() {
this.setDaemon(true);
start();
}
public void run() {
while(true)
if(semaphore == 0) {
// yield();
++semaphore;
// yield();
--semaphore;
// yield();
}
}
public static void main(String args[]) {
new SimpleSemaphore();
new SimpleSemaphore();
new SimpleWatcher();
}
}
class SimpleWatcher extends Thread {
public SimpleWatcher() {
start();
}
public void run() {
while(true) {
int s = SimpleSemaphore.semaphore;
if(s == 0 || s == 1) {
} else {
System.out.println("Irregular Value: " + s);
System.exit(0);
}
}
}
}
Due thread SimpleSemaphore concorrono alla risorsa gestita dal semaforo e un terzo thread, SimpleWatcher, osserva se la variabile semaphore assume valori non validi (diversi da 0 e 1).
Commentando o no yield() e seconda di JVM e OS si possono osservare i valori non validi -1 e 2.
Mi spiego il valore 2 ma non il -1.
Qualcuno me lo spiega?
class SimpleSemaphore extends Thread {
public static volatile int semaphore = 0;
public SimpleSemaphore() {
this.setDaemon(true);
start();
}
public void run() {
while(true)
if(semaphore == 0) {
// yield();
++semaphore;
// yield();
--semaphore;
// yield();
}
}
public static void main(String args[]) {
new SimpleSemaphore();
new SimpleSemaphore();
new SimpleWatcher();
}
}
class SimpleWatcher extends Thread {
public SimpleWatcher() {
start();
}
public void run() {
while(true) {
int s = SimpleSemaphore.semaphore;
if(s == 0 || s == 1) {
} else {
System.out.println("Irregular Value: " + s);
System.exit(0);
}
}
}
}
Due thread SimpleSemaphore concorrono alla risorsa gestita dal semaforo e un terzo thread, SimpleWatcher, osserva se la variabile semaphore assume valori non validi (diversi da 0 e 1).
Commentando o no yield() e seconda di JVM e OS si possono osservare i valori non validi -1 e 2.
Mi spiego il valore 2 ma non il -1.
Qualcuno me lo spiega?