如果你想理解其中的奥妙,请看操作系统的书。
实际上,并不是每一个程序在系统里面都是连续执行的,系统会分时间片来执行不同的线程(你的程序运行起来至少是一个线程),这是由不得java控制的。
运行时,系统会根据当前资源来选择是否执行你的程序。你可以把下面的程序运行多几下,就会发现结果并不是一样的。(在运行前,你可以想想按照你原来的理解应该输出什么结果)总之,结果不同,是系统调用问题,而不是sleep问题。让然,如果你的sleep时间很大,超过了系统时间片轮换时间,就会按照顺序输出(Main里面的改成:Thread.sleep(1000);public class TestThread extends Thread {
private int myId = 0;
TestThread (int i) {
myId = i;
}
public void run(){
try {
System.out.println("This is begin of thread " + myId);
sleep(1);
System.out.println("This is end of thread " + myId);
}
catch(java.lang.InterruptedException e) {
System.out.println("Error in thread " + myId + " : " + e);
}
}
public static void main(String args[]) {
try {
for(int i=0; i<10; i++) {
TestThread test = new TestThread(i);
test.start();
Thread.sleep(1);
}
}
catch(Exception e) {
}
}
}
实际上,并不是每一个程序在系统里面都是连续执行的,系统会分时间片来执行不同的线程(你的程序运行起来至少是一个线程),这是由不得java控制的。
运行时,系统会根据当前资源来选择是否执行你的程序。你可以把下面的程序运行多几下,就会发现结果并不是一样的。(在运行前,你可以想想按照你原来的理解应该输出什么结果)总之,结果不同,是系统调用问题,而不是sleep问题。让然,如果你的sleep时间很大,超过了系统时间片轮换时间,就会按照顺序输出(Main里面的改成:Thread.sleep(1000);public class TestThread extends Thread {
private int myId = 0;
TestThread (int i) {
myId = i;
}
public void run(){
try {
System.out.println("This is begin of thread " + myId);
sleep(1);
System.out.println("This is end of thread " + myId);
}
catch(java.lang.InterruptedException e) {
System.out.println("Error in thread " + myId + " : " + e);
}
}
public static void main(String args[]) {
try {
for(int i=0; i<10; i++) {
TestThread test = new TestThread(i);
test.start();
Thread.sleep(1);
}
}
catch(Exception e) {
}
}
}
--因为每个子线程要sleep10毫秒,而主线程只有3毫秒,程序就结束)同理,若改为13,结果又会不同
说了这么多,有点乱,希望你能理会-------我也在学thinking,一起加油吧!