我想澄清我对线程调度的概念。我之前曾问过这个问题,但由于没有回应,我试图以方便的方式问它我的系统有 4 个处理器,当我在一个线程上运行单个 CPU 绑定任务时,它在大约 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();
}
}