为什么执行下面的程序后,结果不是有序的?按理说加了锁以后输出的结果应该是按顺序输出啊?当时当我把锁加到
public void run下的时候,结果又是有序的?怎么回事啊,求大虾解释
public class ThreadTest1 {
public static void main(String[] args) { MyThread mt = new MyThread();
new Thread(mt).start(); // 通过实现Runnable的类的对象来开辟第一个线程
new Thread(mt).start(); // 通过实现Runnable的类的对象来开辟第二个线程
new Thread(mt).start(); // 通过实现Runnable的类的对象来开辟第三个线程
// 由于这三个线程是通过同一个对象mt开辟的,所以run()里方法访问的是同一个index
}
}class MyThread implements Runnable { // 实现Runnable接口
volatile int index = 20;
boolean flag = false;
public void run() {
for (;;) {
System.out.println(Thread.currentThread().getName() + ":"
+ getNum());
}
} public int getNum() {
synchronized(this){
if (index <= 0) {
throw new RuntimeException("错拉!");
}
index--;
return index;
}
}
}