Java - 线程优先级方法& main()中的其他各种方法

时间:2014-04-03 20:48:05

标签: java multithreading

我有以下代码:

 class PrintThread extends Thread
 {
 private int sleepTime;
 public PrintThread( String name )
 {
 super( name );
 sleepTime = (int) ( Math.random( ) * 15000 );
 System.err.println( "Name:"+getName( )+";sleep: " + sleepTime );
 }
public void run( )
{
try
{
  System.err.println( getName( ) + " going to sleep" );
  Thread.sleep( sleepTime );
}
catch ( InterruptedException interruptedException )
{
  System.err.println( interruptedException.toString() );
}
System.err.println( getName( ) + " done sleeping" );
}
}
public class ThreadTester
{
public static void main( String args[] )
{
PrintThread thread1, thread2, thread3, thread4;
thread1 = new PrintThread( "thread1" );
thread2 = new PrintThread( "thread2" );
thread3 = new PrintThread( "thread3" );
thread4 = new PrintThread( "thread4" );
System.err.println( "\nStarting threads" );
thread1.start();
thread2.start();
thread3.start();
thread4.start();
System.err.println( "Threads started\n" );
}
}

每次运行时,输出都与上一次运行不同。 例如 RUN1:

Name:thread1;sleep: 5608
Name:thread2;sleep: 2007
Name:thread3;sleep: 7443
Name:thread4;sleep: 1601

Starting threads
thread2 going to sleep
Threads started

thread1 going to sleep
thread4 going to sleep
thread3 going to sleep
thread4 done sleeping
thread2 done sleeping
thread1 done sleeping
thread3 done sleeping

RUN2:

Name:thread1;sleep: 2033
Name:thread2;sleep: 4896
Name:thread3;sleep: 1217
Name:thread4;sleep: 150

Starting threads
Threads started

thread2 going to sleep
thread3 going to sleep
thread1 going to sleep
thread4 going to sleep
thread4 done sleeping
thread3 done sleeping

为什么System.err.println("线程开始\ n");有时在任何其他线程之前执行,&有时在thread1.start()之后; ?! 我知道线程有优先级问题,但这适用于我知道的彼此之间的线程!

1 个答案:

答案 0 :(得分:0)

当你启动一个线程时,它几乎可以立即发生,即在下一行执行之前,有时它有一个小的延迟,可能是几毫秒,所以它会出现在输出的后面。

线程需要一段随机的时间来实际启动。