有關虛擬機(以及一般生活)非常寶貴的一件事是抽象。線程的執行時間不會因內核數量而有所不同;不是在Linux中,也不在Windows中......我希望我不會誤解你的問題。
(雖然我使用的currentTimeMillis(),nanotime是在不同的尺度相同,當然)
檢查下列例子我製作:
public class SynchThreads {
public static void main(String[] args) throws InterruptedException {
GreedyTask gtA = new GreedyTask("A");
GreedyTask gtB = new GreedyTask("B");
Thread a = new Thread(gtA);
Thread b = new Thread(gtB);
a.start();
b.start();
a.join();
b.join();
System.out.println(gtA.toString()+" running time: "+gtA.getRunningTime());
System.out.println(gtB.toString()+" running time: "+gtB.getRunningTime());
}
private static class GreedyTask implements Runnable {
private long startedTime, finishedTime, totalRunTime;
private String myName;
public GreedyTask(String pstrName) {
myName = pstrName;
}
public void run() {
try {
startedTime = System.currentTimeMillis();
randomPowerNap(this);
finishedTime = System.currentTimeMillis();
totalRunTime = finishedTime - startedTime;
} catch (Exception e) { System.err.println(e.getMessage()); }
}
public String toString() { return ("Task: " + myName); }
public long getRunningTime() { return this.totalRunTime; }
}
private static synchronized void randomPowerNap(GreedyTask gt) throws InterruptedException {
System.out.println("Executing: "+gt.toString());
long random = Math.round(Math.random()*15000);
System.out.println("Random time for "+gt+" is: "+random);
Thread.sleep(random);
}
}
下面是一個輸出在4個內核的Windows機器運行:
:
Executing: Task: A
Random time for Task: A is: 1225
Executing: Task: B
Random time for Task: B is: 4383
Task: A running time: 1226
Task: B running time: 5609 // what's funny about this? this is equal to Btime - Atime
這是在一個4個核的Linux機器上運行
Executing: Task: A
Random time for Task: A is: 13577
Executing: Task: B
Random time for Task: B is: 5340
Task: A running time: 13579
Task: B running time: 18920 // same results
結論:B總時間增加了必須等待的時間,而randomPowerNap被A阻止,因此由於虛擬機的硬件抽象,線程看到它們的運行時間沒有差異,因爲它們都運行在' VIRTUAL BIG CORE',如果你知道我的意思。
我希望這有助於。
來源
2014-08-27 14:49:26
Fer