public class CreateThreadRunnableExample implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Child Thread : " + i);
try {
Thread.sleep(50);
} catch (InterruptedException ie) {
System.out.println("Child thread interrupted! " + ie);
}
}
System.out.println("Child thread finished!");
}
public static void main(String[] args) {
Thread t = new Thread(new CreateThreadRunnableExample(), "My Thread");
t.start();
for (int i = 0; i < 5; i++) {
System.out.println("Main thread : " + i);
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
System.out.println("Child thread interrupted! " + ie);
}
}
System.out.println("Main thread finished!");
}
}
在这个程序中,使用了两种不同时间的睡眠方法..,,,所以如果主线程运行时间那么子线程必须运行2次。但它只运行一次......我们采用可运行或运行的概念状态......然后当主线程结束时,2个子线程将处于就绪状态,那么为什么只有一个子线程运行。