我想检查多线程是否比单线程快,然后我在这里做了一个演示:
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
我的问题是:
- SecondThreadStart比singleThreadStart花费更多的时间,是因为创建线程的成本吗?
- 尽管创建线程的成本很高,但CPU数量是4,那么使用超过4个线程会比使用四个线程慢吗?
- 如果我想做一些需要更多时间的事情,使用四个线程来做是最好的吗?