Verständnis flüchtiges Schlüsselwort dieses Programm:flüchtige Stichwort: Need Erklärung für dieses Programmverhalten
public class VolatileExample implements Runnable{
private volatile int vol;
@Override
public void run(){
vol=5;
while(vol==5)
{
System.out.println("Inside run when vol is 5. Thread is : "+Thread.currentThread().getName());
if("t2".equals(Thread.currentThread().getName()))
{
System.out.println("Got Thread : "+Thread.currentThread().getName()+" Now Calling Stop To End This Flow");
stopIt();
}
}
}
public void stopIt(){
vol=10;
}
public static void main(String[] args){
VolatileExample ve1 = new VolatileExample();
VolatileExample ve2 = new VolatileExample();
Thread t1 = new Thread(ve1);
Thread t2 = new Thread(ve1); //t1 and t2 operate on same instance of VolatileExample class
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
Ausgang:
Inside run when vol is 5. Thread is : t1
Inside run when vol is 5. Thread is : t1
Inside run when vol is 5. Thread is : t2
Inside run when vol is 5. Thread is : t1
Got Thread : t2 Now Calling Stop To End This Flow
Inside run when vol is 5. Thread is : t1
Alle schreiben vol Variable wird sofort in dem Hauptspeicher geschrieben werden und sollte "sichtbar" für andere Threads sofort. Warum t1 Thread immer noch ausgeführt wird, nachdem stopIt() aufgerufen wurde? Kann es nicht sehen, dass der Vol-Wert jetzt 10 und nicht 5 ist?
Warum haben Sie 've2'? Willst du uns oder dich selbst verwirren? – shmosel
** Geständnis **: Ich wurde verwirrt !!! – Batty
Ich habe das Programmverhalten früher mit Ve2 überprüft, aber für dieses Beispiel verwende ich nur ve1 –