将数据拆分为实现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