public class Test extends Thread{    private static int i;
    Test(){        setPriority(10);    }    public void run(){        System.out.println(Thread.currentThread().getName()+"Another thread starting up. "+i);        while(true){ }    }    public static void main(String[] args){        Test hp1= new Test();        Test hp2= new Test();        Test hp3= new Test();        hp1.start();        hp2.start();        hp3.start();    }}请问线程hp1,hp2,hp3的执行情况,是都执行,还是只执行hp1,还是与执行平台有关呢?顺便解释一下输出的顺序问题。

解决方案 »

  1.   

    若把输出语句改为:
     System.out.println(Thread.currentThread().getName()+"Another thread starting up. "+i++);
    发现输出结果为:
           
       thread-0 Another thread starting up. 0
       thread-1 Another thread starting up. 1
       thread-2 Another thread starting up. 2   或
        
         thread-0 Another thread starting up. 0
        thread-1 Another thread starting up. 2
        thread-2 Another thread starting up. 1 第一种结果不难理解,但如何理解第二种输出结果,为什么先输出i=2,再输出i=1呢? 
      

  2.   

    若把输出语句改为:
     System.out.println(Thread.currentThread().getName()+"Another thread starting up. "+i++);
    发现输出结果为:
           
       thread-0 Another thread starting up. 0
       thread-1 Another thread starting up. 1
       thread-2 Another thread starting up. 2   或
        
         thread-0 Another thread starting up. 0
        thread-1 Another thread starting up. 2
        thread-2 Another thread starting up. 1 第一种结果不难理解,但如何理解第二种输出结果,为什么先输出i=2,再输出i=1呢? 
      

  3.   

    若把输出语句改为:
     System.out.println(Thread.currentThread().getName()+"Another thread starting up. "+i++);
    发现输出结果为:
           
       thread-0 Another thread starting up. 0
       thread-1 Another thread starting up. 1
       thread-2 Another thread starting up. 2   或
        
         thread-0 Another thread starting up. 0
        thread-1 Another thread starting up. 2
        thread-2 Another thread starting up. 1 第一种结果不难理解,但如何理解第二种输出结果,为什么先输出i=2,再输出i=1呢? 
      

  4.   

    可以理解为:线程1比线程2后得到CPU分配时间,因此后输出。
    注意,采用System.out时也是需要进行同步的(隐含同步)。
      

  5.   

    楼上意思是:先进行自加操作,然后再获得CPU时间吗?这个太难理解了吧,线程应该一旦进入run()方法后,即获得CPU开始运行了吧。不知我理解了楼上意思了吗?
      

  6.   

    hp1、hp2、hp3看上去是同步执行的,但是对CPU来说不是,
    CPU会为hp1、hp2、hp3分配执行时间段,也就是说:如当前正在执行hp1,系统默认给它分配的执行时间是20ms,当hp1执行了20ms还未完毕时,系统将保存hp1当前执行到了哪,而去执行hp2或hp3,当hp2、hp3的执行时间段过后才回继续去执行hp1 20ms,这样一直到执行完毕
    其实你可以往hp1、hp2、hp3各放入一个的循环数字,输出一下看看是什么效果就明白了
      

  7.   


    首先,下面的这个语句并不是一个原子操作:
    System.out.println(Thread.currentThread().getName()+"Another thread starting up. "+i++); 
    他的执行顺序是:
    先计算Thread.currentThread().getName()
    ...
    计算i++
    ...
    执行System.out.println所以可知是thread-2是第二个执行i++的,但是第三个执行System.out.println....