Java线程的问题(执行次序的疑惑?) 程序主体如下: package test; public class ThreadRangbu { public static void main(String[] args) throws Exception { Thread01 thread01 = new Thread01(); thread01.start(); for (int i =0; i<5;i++){ try{ Thread.currentThread().sleep(100); System.out.println(Thread.currentThread().getName() +" is executing!"); //System.out.println("i="+i); } catch (Exception e){ } } } } class Thread01 extends Thread{ public void run(){ for (int i =0; i<5;i++){ try{ Thread.currentThread().sleep(100); }catch(Exception e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() +" is running!"); //System.out.println("i="+i); if (i%2==0){ Thread.yield(); System.out.println("Terminate current sub-thread."); } } } } 教科书上的结论说程序运行结果应该是是: main is executing! Thread-0 is running! Thread-0 is running! main is executing! Terminate current sub-thread. main is executing! Thread-0 is running! main is executing! Thread-0 is running! Terminate current sub-thread. 而程序实际运行的结果如下: Thread-0 is running! main is executing! Terminate current sub-thread. Thread-0 is running! main is executing! Thread-0 is running! main is executing! Terminate current sub-thread. main is executing! Thread-0 is running! Thread-0 is running! main is executing! Terminate current sub-thread.
疑问一: 究竟哪个结果才是正确的?
当红色字体部分取消注释时,结果如下: main is executing! Thread-0 is running! i=0 Terminate current sub-thread. main is executing! Thread-0 is running! i=1 main is executing! Thread-0 is running! i=2 Terminate current sub-thread. main is executing! Thread-0 is running! i=3 main is executing! Thread-0 is running! i=4 Terminate current sub-thread.
疑问二:为什么会产生这个变化?
当红色和蓝色字体都取消注释时,结果如下: Thread-0 is running! i=0 main is executing! i=0 Terminate current sub-thread. main is executing! i=1 Thread-0 is running! i=1 Thread-0 is running! i=2 main is executing! i=2 Terminate current sub-thread. Thread-0 is running! i=3 main is executing! i=3 Thread-0 is running! i=4 main is executing! i=4 Terminate current sub-thread.
疑问三:同疑问二,为什么取消注释又有了这样的变化?
总的疑问:对java中线程的执行处理次序不是很明白。以原程序为例(注释两行的程序)我的理解如下: 主方法中“Thread01 thread01 = new Thread01();thread01.start();”创建新的实例thread01,并且调用thread01中的方法run(),其中因为有“System.out.println(Thread.currentThread().getName() +" is running!");”语句,所以程序第一行应该是Thread-0 is running! 此时i=0,故返回主线程,因“System.out.println(Thread.currentThread().getName() +" is executing!");”语句,得到main is executing! 然后返回执行run()得到“Terminate current sub-thread.”结果。 之后i递增,返回main中运行程序,得到与书中不符的结果。 请问高手,我的理解是否正确? 如果有错误,哪里理解存在问题? 请帮我指点一下,谢谢。