Hallo ich übe gerade Threadsynchronisation und eine Sache verstehe ich nicht ganz.
Ich setze den Thread T-Zaehler, methode
als nicht Daemon und den Thread T-Stopper, methode
als Daemon.
Ich dachte der Daemon Thread stoppt sofort wenn main zu ende ist und somit wäre die variable stop nicht auf true gesetzt. Thread Z-Zaehler sollte doch dann endlos weiter laufen...
Wenn ich aber das programm ausführe bekomme ich folgendes:
Kann jemand bitte erklären warum?
Danke schon mal.
Ich setze den Thread T-Zaehler, methode
Code:
work()
Code:
doit()
Ich dachte der Daemon Thread stoppt sofort wenn main zu ende ist und somit wäre die variable stop nicht auf true gesetzt. Thread Z-Zaehler sollte doch dann endlos weiter laufen...
Wenn ich aber das programm ausführe bekomme ich folgendes:
main start
main ende
zaehle: 0
ich warte...
zaehle: 1
ich warte...
zaehle: 2
ich warte...
zaehle: 3
ich warte...
zaehle: 4
ich warte...
zaehle: 5
ich warte...
zaehle: 6
ich warte...
zaehle: 7
ich warte...
zaehle: 8
ich warte...
zaehle: 9
Kann jemand bitte erklären warum?
Java:
public class Synchronisation {
// public boolean stop = false;
// public int i = 0;
public volatile boolean stop = false;
public volatile int i = 0;
public void work(){
Thread th = new Thread("T-Zaehler"){
@Override
public void run() {
while(!stop){
System.out.println("zaehle: "+ i++);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
//
}
}
};
};
th.setDaemon(false);
th.start();
}
public void doit(){
Thread th = new Thread("T-Stopper"){
@Override
public void run() {
while(i != 10){
System.out.println("ich warte...");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
//
}
}
stop = true;
};
};
th.setDaemon(true);
th.start();
}
public static void main(String[] args) {
System.out.println("main start");
Synchronisation s = new Synchronisation();
s.work();
s.doit();
System.out.println("main ende");
}
}
Danke schon mal.