[英]Is multithreading faster than single thread?
我想檢查多線程是否比單線程快,然后我在這里做一個演示:
public class ThreadSpeedTest {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("cpu number:"
+ Runtime.getRuntime().availableProcessors());
singleThreadStart();
// secondThreadStart();
// fiveThreadStart();
}
private static void sum() {
long sum = 0;
for (int i = 0; i < 1000000; i++) {
sum += i;
}
System.out.println(sum);
}
private static void singleThreadStart() {
new Thread(new Runnable() {
public void run() {
long start = System.nanoTime();
// sum();
// sum();
// sum();
sum();
sum();
long end = System.nanoTime();
System.out.println("cost time:" + (end - start));
}
}).start();
}
private static void secondThreadStart() {
long start = System.nanoTime();
Thread thread1 = new Thread(new Runnable() {
public void run() {
sum();
}
});
thread1.start();
Thread thread2 = new Thread(new Runnable() {
public void run() {
sum();
}
});
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.nanoTime();
System.out.println("cost time:" + (end - start));
}
private static void fiveThreadStart() {
long start = System.nanoTime();
Thread thread1 = new Thread(new Runnable() {
public void run() {
sum();
}
});
thread1.start();
Thread thread2 = new Thread(new Runnable() {
public void run() {
sum();
}
});
thread2.start();
Thread thread3 = new Thread(new Runnable() {
public void run() {
sum();
}
});
thread3.start();
Thread thread4 = new Thread(new Runnable() {
public void run() {
sum();
}
});
thread4.start();
Thread thread5 = new Thread(new Runnable() {
public void run() {
sum();
}
});
thread5.start();
try {
thread1.join();
thread2.join();
thread3.join();
thread4.join();
thread5.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.nanoTime();
System.out.println("cost time:" + (end - start));
}
}
首先我用兩個 sum 方法運行 singleThreadStart,結果是
cpu number:4
499999500000
499999500000
cost time:6719000
然后我運行secondThreadStart,結果是
cpu number:4
499999500000
499999500000
cost time:14299000
然后我用五個 sum 方法運行 singleThreadStart,結果是
cpu number:4
499999500000
499999500000
499999500000
499999500000
499999500000
cost time:10416000
最后我運行了 FiveThreadStart,結果是
cpu number:4
499999500000
499999500000
499999500000
499999500000
499999500000
cost time:15708000
我的問題是:
1.SecondThreadStart比singleThreadStart花費更多的時間,是不是因為創建線程的成本?
當然,創建線程是有開銷的。
2.cpu數為4,盡管創建線程有成本,所以使用4個以上的線程數會比使用4個線程慢嗎?
如果線程完成得非常快(不受 IO 限制和 CPU 限制),即使線程數多於 CPU 內核數,您也可以獲得良好的結果。
3.如果我想做一些花費很多時間的事情,使用四個線程來做最好嗎?
您可以使用高級 Java 並發類( newWorkStealingPool
of Executors
)
請參閱此 SE 問題:
Java 的 Fork/Join 與 ExecutorService - 何時使用哪個?
一般情況下:
多線程可以通過使用更多的 CPU 能力來提高應用程序的吞吐量。
這取決於很多因素。
如果您的應用程序是多線程將提供出色的結果
更少的 CPU 綁定,更少的 IO 綁定(但仍然可以為這些應用程序使用多線程)
沒有共享數據
如果不是,則性能取決於上述因素,單線程應用程序和多線程應用程序之間的吞吐量會有所不同。
一些很好的 SE 問題:
好文章:
java-性能文章
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.