I have a java app, and, I want it to take advantage of multicore processors, how do I take advantage of them? Does just s开发者_如何学JAVApawning a new thread do the trick? Like does the OS decide what core to put the thread on?
Yes, the OS has complete control on what core to put your threads on (at least in Java). You shouldn't worry about such things. :) Just spawn your threads and let the OS do the work.
If you want to take the advantage of multi-core processors, try to identify places where you can run codes in parallel. Then create Threads for parallel codes. You don't need to think about allocation of Threads for processor cores, OS will do it.
Like others say, the scheduling itself is done by the OS automatically.
But you still need to think about threading strategy. For example, should you just go with a single thread, since it will be sufficient for your problem? Or should you use available-core number of threads because your algorithm spends most time on a CPU intensive calculation? Or should you use something more like 2*available-core number of threads because there is some network involved? Should you go with a re-sizable cached thread pool? If so, how many thread to maintain when there is no work load, how long to maintain a bigger pool size after the workload increased transiently, etc. etc.
Simple rule of thumb is, 1) go with single thread unless you have a reason to go with multi-threading, 2) Make thread pool size configurable, then find good enough pool size by trial and error (I tend to just use fixed size thread pools because it makes matters simple).
As others have said, the operating system determines how many cores your application gets to use, and deals with allocation of Java threads to cores. So, the first order answer is just to create the threads and let the operating system deal with it.
But be careful. If you just create "lots of threads", the chances are that your application won't go faster. Indeed, it is pretty much guaranteed that there is a point beyond which new threads will actually make your application slower. (Unfortunately, that point is application specific ... and hard to predict.)
To effectively take advantage of multi-core processors, you need to:
- design your application so that there are useful largish tasks that can be done in parallel,
- design your data structures and algorithm to avoid concurrency bottlenecks,
- use thread pools or something similar to avoid an explosion of the number of threads,
- profile and tune the application.
精彩评论