class MyThread implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName());
}
}
}
public class Test {
public static void main(String[] args) {
MyThread my = new MyThread();
Thread t = new Thread(my,"thread-a");
t.start();
for(int i=0;i<100;i++){
System.out.println(i);
if(i>50){
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
代码如上, 我知道在i>50 会强制t运行, 但是t.start()时 线程t 不就已经启动了吗?为什么在i<50时不会输出thread-a
?
你看到的只是你单次运行的结果罢了(由于线程调度,可能使得 i > 50 之后才开始输出 thread-a),你多运行几次就可以看到你想要的结果了:
