Multithreading Costs [多线程所花费的代价]

Descriptions:
java 并发文档翻译,文章链接地址 http://tutorials.jenkov.com/java-concurrency/costs.html


Going from a singlethreaded to a multithreaded application doesn’t just provide benifits.
将单线程程序修改成多线程好处是有的,但同时也会带来其他方面的损失。

It also has some costs. Don’t just multithread-enable an application just because you can.
使用多线程需要为之付出相应的代价。 不要仅仅因为你会多线程便去在编程中使用这种技术。

You should have a good idea that the benefits gained by doing so, are larger than the cost.
在使用之前你应该明确的知道相比于应用多线程所花费的代价,你能够获得更大的收益(的时候再来决定将多线程加入到你的程序中)。

When in doubt, try measuring the performance or responsiveness of the application, instead of just guessing.
如果你不能很好的做出决断,那么试着权衡一下程序的性能或是响应能力在使用多线程技术前后有何变化,而不是仅仅通过猜测的方式来决定是否使用(多线程)。

More complex design

设计更加复杂

Though some parts of a multithreaded applications is simpler than a singlethreaded application, other parts are more complex.
虽然多线程应用程序在某些地方的实现要比单线程应用程序要简单的多,但是其他地方的设计要远比单线程设计复杂得多。

Code executed by multiple threads accessing shared data need special attention.
被多线程执行的访问共享数据的代码端需要给予高度重视。

Thread interaction is far from always simple.
线程之间的交互要远比想象的复杂。

Errors arising from incorrect thread synchronization can be very hard to detect, reproduce and fix.
线程同步操作所引发的错误很难被探知,重现或是修复。

Context Switching Overhead

过渡上下文切换

When a CPU switches from executing one thread to executing another, the CPU needs to save the local data, program pointer etc. of the current thread, and load the local data, program pointer etc. of the next thread to execute.
当 CPU 从一个正在执行的线程切换去执行另一个线程的时候,这个 CPU 需要存放当前线程的本地数据,程序指针等信息; 然后加载另一个将要执行的线程中的本地数据,程序指针等信息。

This switch is called a “context switch”.
上面所描述的切换就叫做 “上下文切换”。

The CPU switches from executing in the context of one thread to executing in the context of another.
对于 CPU 来说,它从正在运行线程的上下文中切换到另一个即将运行的线程的上下文中。

Context switching isn’t cheap.
上下文切换的花费高昂。

You don’t want to switch between threads more than necessary.
所以不到万不得已,我认为你是不会在两个线程之间进行上下文切换的。

You can read more about context switching on Wikipedia:
你可以通过查阅维基百科来获取更多关于上下文切换相关的知识:

http://en.wikipedia.org/wiki/Context_switch

Increased Resource Consumption

增加资源消耗

A thread needs some resources from computer in order to run.
一个线程需要从计算机中获取相应资源以便于能够运行起来。

Besides CPU time a thread needs some memory to keep its local stack.
除此之外,线程在获取到 CPU 资源之后需要额外的内存空间来存放它的本地栈。

It may also take up some resources inside the operating system needed to manage the thread.
线程或许也会在用来管理线程的操作系统内部占据一些资源。

Try creating a program that creates 100 thread that does nothing but wait, and see how much memory the application takes when running.
(你可以)试着创建一个包含100个不做任何事情且仅处于等待状态的线程的程序,然后观察一下该程序运行起来的时候它总共消耗多少内存。