我有一个简单的多线程方法,如下所示:
int processors=Runtime.getRuntime().availableProcessors();
detectors[] theCores = new detectors[processors];
for(int i = 0; i < processors; i++){
theCores[i] = new detectors();
theCores[i].start();
}
for(int i = 0; i < processors; i++){
try{ // Waits for completion of all cores
theCores[i].join();}
catch(InterruptedException IntExp) {}
}
使用.join();意味着已完成的线程将暂停,直到所有线程完成。由于所有线程的速度并不相同,因此某些线程会先于其他线程完成,并且有时最快的线程与最慢的线程完成该方法所需的时间之间存在相当大的差距。有什么方法可以分配已完成并等待的核心来帮助执行剩余的线程吗?
最佳答案
了解Fork/Join在 Java 7 中
The fork/join framework is distinct because it uses a work-stealing algorithm. Worker threads that run out of things to do can steal tasks from other threads that are still busy.
关于Java多线程使用.join();您可以分配空闲线程来帮助仍在运行的线程吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22930508/