我有这段代码使用Java Thread:
public class ThreadExample implements Runnable{
public Thread thread;
static int i = 0;
ThreadExample(){
thread = new Thread(this);
thread.start();
}
public static void main(String[] args) {
ThreadExample example = new ThreadExample();
for(int n =0; n<1000; n++){
System.out.println("main thread "+i);
i++;
}
}
public void run(){
for(int index=0; index<1000; index++){
System.out.println("Sub thread "+i);
i++;
}
}
}
运行时,结果是:
main thread 0
Sub thread 0
Sub thread 2
Sub thread 3
Sub thread 4
Sub thread 5
Sub thread 6
Sub thread 7
Sub thread 8
Sub thread 9
Sub thread 10
Sub thread 11
Sub thread 12
main thread 1
....
我知道运行的线程不遵循它的顺序。但是,我不明白的是:为什么主线程打印 1 (它打印变量 i),当变量 i 达到 12 时?(因为子线程已打印到 12)。
谢谢 :)