在启动一个新线程的时候会有一定时间的额外开销,因此并不是所有情况下都应使用多线程。如下的代码段进行简单实验探讨:
//TimeCostToStartNewThread.java public class TimeCostToStartNewThread{ public static void main(String[] args){ long now1 = System.nanoTime(); for(int i = 0; i < 10000000; i++){// i依次取值100,1000,10000,100000,1000000,10000000 } long current1 = System.nanoTime(); System.out.println("current - now 1 = " + (current1 - now1)); long now2 = System.nanoTime(); new Thread(new Runnable(){ public void run(){ for(int i = 0; i < 10000000; i++){ } } }).start(); long current2 = System.nanoTime(); System.out.println( "current - now 2 = " + (current2 - now2)); } }
D:\CodingLearning\Java多线程设计>javac TimeCostToStartNewThread.java
D:\CodingLearning\Java多线程设计>java TimeCostToStartNewThread
current - now 1 = 906
current - now 2 = 427110
D:\CodingLearning\Java多线程设计>javac TimeCostToStartNewThread.java
D:\CodingLearning\Java多线程设计>java TimeCostToStartNewThread
current - now 1 = 4527
current - now 2 = 435864
D:\CodingLearning\Java多线程设计>javac TimeCostToStartNewThread.java
D:\CodingLearning\Java多线程设计>java TimeCostToStartNewThread
current - now 1 = 45277
current - now 2 = 394511
D:\CodingLearning\Java多线程设计>javac TimeCostToStartNewThread.java
D:\CodingLearning\Java多线程设计>java TimeCostToStartNewThread
current - now 1 = 419263
current - now 2 = 456993
D:\CodingLearning\Java多线程设计>javac TimeCostToStartNewThread.java
D:\CodingLearning\Java多线程设计>java TimeCostToStartNewThread
current - now 1 = 683679
current - now 2 = 429525
D:\CodingLearning\Java多线程设计>javac TimeCostToStartNewThread.java
D:\CodingLearning\Java多线程设计>java TimeCostToStartNewThread
current - now 1 = 3157601
current - now 2 = 447938
D:\CodingLearning\Java多线程设计>
从上面的结果上我们可以得知启动一个新线程的额外开销大约在4*(10的6次方)纳秒的时间,当使用顺序编程的开销时间大于这个值时,我们可以考虑使用多线程。