class MyThread implements Runnable{
private int num = 5;
public void run(){
while(num>0) {
System.out.println(Thread.currentThread().getName()+"--->"+this.num);
num--;
}
}
}
public class test{
public static void main(String[] args) {
MyThread mt1 = new MyThread();
new Thread(mt1,"Number 1").start();
new Thread(mt1,"Number 2").start();
}
}
first of all, the code is easy to understand, but when I compile and run, I am curious about the results, as shown in the figure. but why output 5 twice? . This is different from the answer I read in the book.
new Thread(mt1,"Number 3").start();
just learned java, has doubts about this. Isn"t num a shared global variable for these threads? Second, shouldn"t locking mechanisms be provided between these threads? (I inferred from the output of 1234) how can several threads access the same num at the same time?
I hope you guys can help me with this vegetable chicken, thank you.