有多个线程在操作时,如果系统只有一个CPU,则它根本不可能真正同时进行一个以上的线程,它只能把CPU运行时间划分成若干个时间段,再将时间段分配给各个线程执行,在一个时间段的线程代码运行时,其它线程处于挂起状态.这种方式我们称之为并发(Concurrent).
当系统有一个以上CPU时,则线程的操作有可能非并发.当一个CPU执行一个线程时,另一个CPU可以执行另一个线程,两个线程互不抢占CPU资源,可以同时进行,这种方式我们称之为并行(Parallel)
多线程在并发和并行环境中的不同作用
在并发环境时,多线程不可能真正充分利用CPU,节约运行时间,它只是以”挂起->执行->挂起”的方式以很小的时间片分别运行各个线程,给用户以每个线程都在运行的错觉.在这种环境中,多线程程序真正改善的是系统的响应性能和程序的友好性.
在并行环境中, 一个时刻允许多个线程运行,这时多线程程序才真正充分利用了多CPU的处理能力, 节省了整体的运行时间.在这种环境中,多线程程序能体现出它的四大优势:充分利用CPU,节省时间,改善响应和增加程序的友好性.
PS:在多核时代来临后,开发多线程程序的能力更是每个程序员都该具备的.
前者是逻辑上的同时发生(simultaneous),而后者是物理上的同时发生.
来个比喻:并发和并行的区别就是一个人同时吃三个馒头和三个人同时吃三个馒头。
Concurrency and parallelism are two related to concepts which deals with executing tasks "simultaneously". From Sun's Multithreaded Programming Guide :
Concurrency: A condition that exists when at least two threads are making progress. A more generalized form of parallelism that can include time-slicing as a form of virtual parallelism.
Parallelism: A condition that arises when at least two threads are executing simultaneously.
These two definitions are too formal to be understood easily. On the Internet, there is one image which demonstrates the difference between these two in an easy way:
Much easier to understand,right? For concurrency, tasks can start, run and complete in overlapping the time periods, but they may not run at the same instant, when one task in a queue is running, another task in the other queue will wait. While for parallelism, two tasks can run at the same instant. Concurrency has states which means they know status of other tasks execution, while parallelism is stateless.
With concurrency, we want to improve the responsiveness of the application, with parallelism, we want to improve the utilization efficiency of processors, as the computing speed of a single CPU is driving to its limit, so we try to integrate more processors on a single CPU to distribute tasks among different processors.