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个子线程将处于就绪状态,为什么只有一个子线程运行.