【发布时间】:2016-01-12 17:58:29
【问题描述】:
我想澄清一下我对线程调度的概念。我之前问过this 的问题,但由于没有回应,我试图以方便的方式提出问题。当我在线程上运行单个 CPU 绑定任务时,我的系统有 4 个处理器,它在大约 30 毫秒内完成。当我在两个线程上运行 2 个 CPU 密集型任务时,它们在大约 70 毫秒内完成。
为什么在两个线程上运行 2 个任务需要两倍的时间?
CPU 密集型任务:
public class CpuBoundJob3 implements Runnable {
//long t1,t2;
public void run() {
long t1=System.nanoTime();
String s = "";
String name="faisalbahadur";
for(int i=0;i<10000;i++)//6000 for 15ms 10000 for 35ms 12000 for 50ms
{
int n=(int)Math.random()*13;
s+=name.valueOf(n);
//s+="*";
}
long t2=System.nanoTime();
System.out.println("Service Time(ms)="+((double)(t2-t1)/1000000));
}
}
线程运行任务:
public class TaskRunner extends Thread {
CpuBoundJob3 job=new CpuBoundJob3();
public void run(){
job.run();
}
}
主类:
public class Test2 {
int numberOfThreads=100;//for JIT Warmup
public Test2(){
for(int i=1;i<=numberOfThreads;i++){for JIT Warmup
TaskRunner t=new TaskRunner();
t.start();
}
try{
Thread.sleep(5000);// wait a little bit
}catch(Exception e){}
System.out.println("Warmed up completed! now start benchmarking");
System.out.println("First run single thread at a time");
//run only one thread at a time
TaskRunner t1=new TaskRunner();
t1.start();
try{//wait for the thread to complete
Thread.sleep(500);
}catch(Exception e){}
//Now run 2 threads simultanously at a time
System.out.println("Now run 2 thread at a time");
for(int i=1;i<=2;i++){//run 2 thread at a time
TaskRunner t2=new TaskRunner();
t2.start();
}
}
public static void main(String[] args) {
new Test2();
}
}
【问题讨论】:
-
您的线程可能正在争夺系统资源
-
尽量排除线程创建所涉及的开销。
-
不!线程池也是如此。
-
你在测试单线程情况的时候是不是也使用了线程池?
-
不要为之前的问题创建新的、更糟糕的版本。
标签: java multithreading performance throughput response-time