Ich arbeite am Multi-Threading. In meinem Programm habe ich drei Threads, die man druckt hello1
, fädle zwei Drucke hello2
und fädle drei Drucke hello3
. Ich beginne die die Fäden simultaneously.I der AusgangWie mehrere Threads nacheinander ausgeführt werden
hello1 hello2 hello3 hello1 hello2 sein wollen hello3 und so weiter ...
aber jedes Mal, ich bin mit dem Programm seine verschiedenen geben Ausgänge wie Hallo2 Hallo1 Hallo3, Hallo1 Hallo3 Hallo2. Ich möchte die Ausgabe in einer Sequenz von 1 2 3. werden, um den Code unten
package javaapplication2;
public class ThreadDemo {
void MyThread() {
boolean st = true;
Thread t1 = new Thread() {
@Override
public void run() {
for (int x = 0; x < 8; x++) {
try {
System.out.println("hello " + 1);
wait();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
};
//thread 2
Thread t2 = new Thread() {
@Override
public void run() {
for (int x = 0; x < 8; x++) {
try {
System.out.println("hello " + 2);
//Thread.sleep(2000);
wait();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
};
//thraed 3
Thread t3 = new Thread() {
@Override
public void run() {
for (int x = 0; x < 8; x++) {
try {
System.out.println("hello " + 3);
Thread.sleep(2000);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
};
t1.start();
try{
t1.join();
}catch (Exception e){
}
t2.start();
try{
t2.join();
}catch (Exception e){
}
t3.start();
try{
t3.join();
}catch (Exception e){
}
}
public static void main(String[] args) {
new ThreadDemo().MyThread();
}
}
Was ist der Sinn der Verwendung von Threads, wenn Sie sie nacheinander ausführen? – Reimeus
Sie ignorieren nur alle Ausnahmen, die sich aus dem Aufruf von 'wait()' außerhalb eines Synchronisierungsblocks ergeben? – Kayaman
Sie brauchten eine geeignete Synchronisation, schauen Sie sich die CyclicBarrier-Klasse an https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CyclicBarrier.html – DaysLikeThis