一个java中的多线程的问题!
package cn.junco.mutilthread;
public class ThreadTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
PrintThread thread1,thread2,thread3,thread4;
thread1=new PrintThread( "thread1 ");
thread2=new PrintThread( "thread2 ");
thread3=new PrintThread( "thread3 ");
thread4=new PrintThread( "thread4 ");
System.err.println( "\n Starting threads ");
thread1.start();
thread2.start();
thread3.start();
thread4.start();
System.err.println( "Threads started\n ");
}
}
class PrintThread extends Thread
{
private int sleepTime ;
public PrintThread(String name)
{
super(name);
sleepTime=(int)(Math.random()*5000);
System.err.println( "Name: "+getName()+ " sleep: "+sleepTime);
}
public void run()
{
try {
System.err.println(getName()+ " going to sleep ");
Thread.sleep(sleepTime);
} catch (Exception e) {
// TODO: handle exception
}
System.err.println(getName()+ " done sleeping ");
}
}
结果一:Name:thread4 sleep:4023
Starting threads
thread1 going to sleep
Threads started
thread3 going to sleep
thread2 going to sleep
thread4 going to sleep
thread2 done sleeping
thread1 done sleeping
thread3 done sleeping
thread4 done sleeping
结果二:Name:thread1 sleep:4878
Name:thread2 sleep:2999
Name:thread3 sleep:1695
Name:thread4 sleep:7
Starting threads
thread1 going to sleep
Threads started
thread3 going to sleep
thread2 going to sleep
thread4 going to sleep
thread4 done sleeping
thread3 done sleeping
thread2 done sleeping
thread1 done sleeping
问题是为什么Threads started这个输出结果直接的就在thread1 going to sleep 之后
问题2 ,4个thread 的执行顺序的优先级有什么原则吗?
------解决方案--------------------System.err.println在main线程,输出顺序也不是固定的
没有设定优先级,原则上来讲,没有固定的执行顺序