写了段java线程的代码,编码如下:
public class NewThread implements Runnable {
Thread t;
NewThread(){
t = new Thread(this,"Demo Thread");
System.out.println("Child thread: "+t);
t.start();
}
public void run() {
try{
for(int i=5; i>0;i--){
System.out.println("Child Thread: "+i);
Thread.sleep(500);
}
}catch(InterruptedException e){
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
public class ThreadDemo {
public static void main(String[] args) {
new NewThread();
try{
for(int i=5; i>0;i--){
System.out.println("Main Thread: "+i);
Thread.sleep(1000);
}
}catch(InterruptedException e){
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
分别保存在NewThread.java和ThreadDemo.java两个文件中,运行时,发现了两个结果,请问是为什么。
结果如下:第一种结果:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
再次运行时,会发现另一种结果,如下:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Child Thread: 3
Main Thread: 4
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
这两个结果轮流显示,如果第一次结果是第一种情况,那么再执行程序的时候就会是第二种情况,请问为何?我从代码理解应该是第一种情况~

解决方案 »

  1.   

    这么说吧……
    比如在某一秒
    你第一次运行是可能打印10次A 20次B
    第二次是绝对有可能在那一秒里面打印1次A 19次B的……
    这个跟CPU分配到你那个线程的运行时间有关……
      

  2.   

    这代码就不能用 [Java] 那些标签包一下么,看着真费劲!
      

  3.   

    两个线程之间本来就没有联系,输出怎么可能有必然规律呢?
    BTW:你绝不是名门正派,老夫的脑子已经彻底的乱掉了。
      

  4.   

    [JAVA]
    public static void main(String[] args){
        sysout
    }
      

  5.   

         朋友你好,线程肯定每次执行都不一样,如果一样那就是巧合。
    是这样的,每个线程你执行的是根据你CPU分配情况,系统在运行,WINDOWS下有那么进程当然也有很多线程,所以每次运行的时候呢,CPU分配不一样,肯定就不同。顺便告诉你,同一段代码,在不同的机子上也是不同的。如果想要了解清楚建议还是看一下这方面的书
      

  6.   

    你需要了解下线程的4种状态,新状态 也就是你实现了Runable接口或者继承了Thread线程类,说明这个类是线程类。 然后是可运行状态  就是你调用了start函数的时候,就会变为可运行状态,等待CPU为这个线程分配地址并执行,等待的时间是不确定的,所以你的得出的结果就每次都不同,要想实现一样,就必须调用控制线程同步的相关方法,比如sleep write notfily ......  然后就是阻塞状态 和 消亡状态,这两个自己去了解吧!!
      

  7.   

    当你运行程序的时候CPU非常空闲,结果就有可能一样
      

  8.   

    [code=Java][/code
    ]//使用标签退出循环示例
    class breakloop3 { 
      public static void main(String args[]) { 
        int i;    
        for(i=1; i<=3; i++) {
    one:    {
    two:    {
    three:  {
                System.out.println("i is " + i+" now\n");
                if(i==1) break one;
                if(i==2) break two;
                if(i==3) break three;
                System.out.println("won't print");    
              }
              System.out.println("block three finished");
            }
            System.out.println("block two finished");
          }
          System.out.println("block one finished");
        }
        System.out.println("all is over");
      } 
    }