http://download.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html
New in the Java SE 7 release, the fork/join framework is an implementation of the ExecutorService
interface that helps you take advantage of multiple processors.
As with any ExecutorService
, the fork/join framework distributes tasks to worker threads in a thread pool. 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 api,甚至进一步阅读更深入的材料才能学习到全部的知识。
写了一些多线程的小程序以后就能明白,真是心思缜密才能写好啊。
1,事先就必须仔细考虑所有可能的情况。线程间如何交互,如何工作。使用什么方案避免线程间干扰。
2,尤其尤其要注意的是,必须要考虑各种异常如何处理。所有可能出现问题的code都必须catch exception,否则一旦出错很难判断问题所在。
一旦出现异常,必须做好一切后续工作:如关闭stream,关闭线程池,保证运行到一半的程序回到正常状态而不是某个临时状态。这样程序才有不出现混乱,继续运行下去的可能。
3,调试很难,每次运行结果都可能不一样。不同的机器运行结果也可能不同。比如较快的机器可能线程运行没有问题,较慢的机器就会出现问题。
要保证程序稳定性,不要将逻辑正确性建立在某些不稳定的因素上:
例如,逻辑正确性不能依赖sleep的时间,因为sleep随时可能中断。
又比如,逻辑正确性最好不要依赖从concurrent collection取出element的顺序。
再比如,要充分考虑到task运行的时间。逻辑正确性不能建立在认为某个任务应该能够完成的估计上。
总之,任何一个涉及多线程的程序,不论多么小,都应该用十二分的认真去对待。