827*_*827 2 java benchmarking multithreading
文件:Example1.java
public class Example1 implements Runnable {
public void run() {
for(int i = 0; i < 100000000; i++) {
int x = 5;
x = x * 4;
x = x % 3;
x = x + 9000;
x = x * 923;
}
}
public static void task() {
for(int i = 0; i < 100000000; i++) {
int x = 5;
x = x * 4;
x = x % 3;
x = x + 9000;
x = x * 923;
}
for(int i = 0; i < 100000000; i++) {
int x = 9;
x = x * 2;
x = x % 4;
x = x + 3241;
x = x * 472;
}
}
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
Example1.task();
Example1.task();
Example1.task();
Example1.task();
Example1.task();
long stopTime = System.currentTimeMillis();
long runTime = stopTime - startTime;
System.out.println("Run time for one thread: " + runTime);
startTime = System.Example1();
(new Thread(new Example1())).start();
(new Thread(new Example2())).start();
(new Thread(new Example1())).start();
(new Thread(new Example2())).start();
(new Thread(new Example1())).start();
(new Thread(new Example2())).start();
(new Thread(new Example1())).start();
(new Thread(new Example2())).start();
(new Thread(new Example1())).start();
(new Thread(new Example2())).start();
stopTime = System.currentTimeMillis();
runTime = stopTime - startTime;
System.out.println("Run time for two threads: " + runTime);
}
}
Run Code Online (Sandbox Code Playgroud)
文件:Example2.java
public class Example2 implements Runnable {
public void run() {
for(int i = 0; i < 100000000; i++) {
int x = 9;
x = x * 2;
x = x % 4;
x = x + 3241;
x = x * 472;
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行它时,它输出:
一个线程的运行时间:1219
两个线程的运行时间:281
或者非常接近的东西.
为什么会有这样的差异?为什么将它分成两个线程比直接运行它快两倍?
Mal*_*eur 19
你实际上并没有等待线程完成.
一旦启动一个线程,就必须在其上调用.join()以等待它完成.这里发生的是你的所有线程都在启动,一旦最后一个线程启动,你计时它然后计算停止时间.这意味着您的线程仍在后台运行.
编辑:第一个需要这么长时间的原因是因为你正在进行一系列同步调用,而创建一个线程并启动它会产生一个异步任务.
编辑2:这是第一次测试中发生的情况的餐巾序列图:http://www.websequencediagrams.com/cgi-bin/cdraw?lz = TWFpbi0-RXhhbXBsZTE6IFRhc2sgc3RhcnRlZAphY3RpdmF0ZSAAGAgKACEILS0-TWFpbjogZG9uZQpkZQAYEgABWAABWAABgTFlMQo&s=napkin
编辑3:我刚刚意识到第二个序列图将所有箭头指向/ same/thread.它们实际上是不同的线程,每次调用.