Может кто-нибудь помочь мне, как мы можем синхронизировать многопоточную программу Java ниже? Я изучаю Многопоточность в Java, которая является немного сложным предметом, и я получил эту проблему в Интернете и пытался решить ее, но я не могу.Например,
public class GoMyThread {
public static void main(String[] args) {
MyThread t1 = new MyThread("Louis");
MyThread t2 = new MyThread("Mathilde");
MyThread t3 = new MyThread("Toto");
t1.start();
t2.start();
t3.start();
}
}
public class MyThread extends Thread {
public MyThread(String name) {
super(name);
}
public void run() {
for (int i = 0; i < 3; i++)
{
System.out.println(getName() + " Finish , level " + (i+1));
if (getName().compareTo("Louis") != 0)
{
try{
Thread.sleep(100);
}
catch (InterruptedException e){}
}
}
}
}
the out put for this is of the programe changes with every run
, вывод ниже - один из них
Louis Finish , level 1
Louis Finish , level 2
Louis Finish , level 3
Toto Finish , level 1
Mathilde Finish , level 1
Toto Finish , level 2
Mathilde Finish , level 2
Toto Finish , level 3
Mathilde Finish , level 3
what I want is the output to be like ,three of them finish level 1 before passing to the next level ,But i can't achieve it no matter i try ,the
вывод должен выглядеть следующим образом.
Louis Finish , level 1`
Mathilde Finish , level 1
Toto Finish , level 1
Louis Finish , level 2
Toto Finish , level 2
Mathilde Finish , level 2
Toto Finish , level 3
Mathilde Finish , level 3
Louis Finish,level 3
I will appriciate if you give me some concepts to understand java Thread programming too , ,Thank You!