將數據拆分爲實現Runnable的對象,然後將它們傳遞給新線程。
在這種情況下,有四個以上的線程不會消滅你,但你不能獲得比核心更多的並行工作(如註釋中提到的那樣) - 如果線程多於核心,系統將不得不處理誰去的時候。
如果我有一類客戶,我想發出一個線程來8000個客戶放在首要更大集合我可能會做這樣的事情:
public class CustomerClassifier implements Runnable {
private customer[] customers;
public CustomerClassifier(customer[] customers) {
this.customers = customers;
}
@Override
public void run() {
for (int i=0; i< customers.length; i++) {
classify(customer);//critical that this classify function does not
//attempt to modify a resource outside this class
//unless it handles locking, or is talking to a database
//or something that won't throw fits about resource locking
}
}
}
然後發出這些線程別處
int jobSize = 8000;
customer[] customers = new customer[jobSize]();
int j = 0;
for (int i =0; i+j< fullCustomerArray.length; i++) {
if (i == jobSize-1) {
new Thread(new CustomerClassifier(customers)).start();//run will be invoked by thread
customers = new Customer[jobSize]();
j += i;
i = 0;
}
customers[i] = fullCustomerArray[i+j];
}
如果你有你的分類方法會影響同一資源的地方,你將不得不 實現鎖定,也將殺死獲得了一定程度的優勢。
併發是非常複雜的,需要大量的心思,我也建議看oracle的文檔http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html (我知道鏈接是壞的,但希望在Oracle文檔不走動太多?)
免責聲明:我不是併發設計或多線程(不同主題)的專家。
通過實現上述內容,您不會減少計算時間。 – Kon
如果您的工作完全受CPU限制,則您的有效並行性級別將嚴格限制爲CPU內核數量。 – SLaks
確保任何共享狀態都是線程安全的。更好的是,擺脫任何共享狀態。 – SLaks