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,还是与执行平台有关呢?顺便解释一下输出的顺序问题。
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,还是与执行平台有关呢?顺便解释一下输出的顺序问题。
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呢?
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呢?
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呢?
注意,采用System.out时也是需要进行同步的(隐含同步)。
CPU会为hp1、hp2、hp3分配执行时间段,也就是说:如当前正在执行hp1,系统默认给它分配的执行时间是20ms,当hp1执行了20ms还未完毕时,系统将保存hp1当前执行到了哪,而去执行hp2或hp3,当hp2、hp3的执行时间段过后才回继续去执行hp1 20ms,这样一直到执行完毕
其实你可以往hp1、hp2、hp3各放入一个的循环数字,输出一下看看是什么效果就明白了
首先,下面的这个语句并不是一个原子操作:
System.out.println(Thread.currentThread().getName()+"Another thread starting up. "+i++);
他的执行顺序是:
先计算Thread.currentThread().getName()
...
计算i++
...
执行System.out.println所以可知是thread-2是第二个执行i++的,但是第三个执行System.out.println....