我想清除我在线程调度方面的概念。我以前曾问过this问题,但由于没有回复,我试图以方便的方式询问我的系统有4个处理器,当我在一个线程上运行单个CPU绑定任务时,它在大约30ms完成。当我在两个线程上运行2个CPU绑定任务时,它们在大约70ms内完成。
为什么在两个线程上运行的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();
}
}
答案 0 :(得分:-1)
有时会发生的另一种现象是&#34;虚假分享&#34;。当一个线程从另一个线程正在写入的相同高速缓存行(通常是64个连续字节,具体取决于系统)读取时,会发生这种情况。这对缓存不利,这会减慢内存访问速度。
当我编写我的第一个多线程程序时,发生在我身上的情况如下:我分配了一个线程来操作数组的偶数位置,另一个线程操作奇数位置。这是完全线程安全的,但速度很慢,因为当线程1在数组中写入#n时,线程2从地址#(n + 1)读取,这是与地点#n相同的缓存行,所以缓存不断失效。