public class Test implements Runnable { public int threadNum; public void init() {
for(int i=0; i<3; i++) {
Thread t = new Thread(this);
this.threadNum = i;
t.start(); }
} public void run() {
System.out.println("num ------ "+this.threadNum);
} public static void main(String args[]) {
new Test().init();
}
}
大家知道为什么这句执行完后
结果是
num ------ 2
num ------ 2
num ------ 2
为什么得不到 我想要的
num ----- 0
num ----- 1
num ----- 2在线急等了谢谢了
for(int i=0; i<3; i++) {
Thread t = new Thread(this);
this.threadNum = i;
t.start(); }
} public void run() {
System.out.println("num ------ "+this.threadNum);
} public static void main(String args[]) {
new Test().init();
}
}
大家知道为什么这句执行完后
结果是
num ------ 2
num ------ 2
num ------ 2
为什么得不到 我想要的
num ----- 0
num ----- 1
num ----- 2在线急等了谢谢了
这段代码加到for循环里面去就得到你要的结果了
那我该怎么解决呢??
在 t.start();
后加上
try {
t.sleep(100); //让主线程休息
} catch (InterruptedException ex) {
} 就对了
原因就如 cosmos1984所说的那样
再次谢谢